
(function($) {
var _rootUrl = '/', _serverUrl = _rootUrl + 'ezjscore/', _seperator = '@SEPERATOR$';
if ( window.XMLHttpRequest && window.ActiveXObject )
$.ajaxSettings.xhr = function() { try { return new window.ActiveXObject('Microsoft.XMLHTTP'); } catch(e) {} };
function _ez( callArgs, post, callBack )
{
callArgs = callArgs.join !== undefined ? callArgs.join( _seperator ) : callArgs;
var url = _serverUrl + 'call/';
if ( post )
{
if ( post.join !== undefined )
post.push( { 'name': 'ezjscServer_function_arguments', 'value': callArgs } );
else if ( typeof(post) === 'string' )
post += ( post !== '' ? '&' : '' ) + 'ezjscServer_function_arguments=' + callArgs;
else
post['ezjscServer_function_arguments'] = callArgs;
return $.post( url, post, callBack, 'json' );
}
return $.get( url + encodeURIComponent( callArgs ), {}, callBack, 'json' );
};
_ez.url = _serverUrl;
_ez.root_url = _rootUrl;
_ez.seperator = _seperator;
$.ez = _ez;
function _ezLoad( callArgs, post, selector, callBack )
{
callArgs = callArgs.join !== undefined ? callArgs.join( _seperator ) : callArgs;
var url = _serverUrl + 'call/';
if ( post )
post['ezjscServer_function_arguments'] = callArgs;
else
url += encodeURIComponent( callArgs );
return this.load( url + ( selector ? ' ' + selector : '' ), post, callBack );
};
$.fn.ez = _ezLoad;
})(jQuery);
(function($){
})(window.jQuery);
window.log = function(){
log.history = log.history || [];   // store logs to an array for reference
log.history.push(arguments);
if(this.console){
console.log( Array.prototype.slice.call(arguments) );
}
};
(function(doc){
var write = doc.write;
doc.write = function(q){
log('document.write(): ',arguments);
if (/docwriteregexwhitelist/.test(q)) write.apply(doc,arguments);
};
})(document);
(function($,e,b){var c="hashchange",h=document,f,g=$.event.special,i=h.documentMode,d="on"+c in e&&(i===b||i>7);function a(j){j=j||location.href;return"#"+j.replace(/^[^#]*#?(.*)$/,"$1")}$.fn[c]=function(j){return j?this.bind(c,j):this.trigger(c)};$.fn[c].delay=50;g[c]=$.extend(g[c],{setup:function(){if(d){return false}$(f.start)},teardown:function(){if(d){return false}$(f.stop)}});f=(function(){var j={},p,m=a(),k=function(q){return q},l=k,o=k;j.start=function(){p||n()};j.stop=function(){p&&clearTimeout(p);p=b};function n(){var r=a(),q=o(m);if(r!==m){l(m=r,q);$(e).trigger(c)}else{if(q!==m){location.href=location.href.replace(/#.*/,"")+q}}p=setTimeout(n,$.fn[c].delay)}$.browser.msie&&!d&&(function(){var q,r;j.start=function(){if(!q){r=$.fn[c].src;r=r&&r+a();q=$('<iframe tabindex="-1" title="empty"/>').hide().one("load",function(){r||l(a());n()}).attr("src",r||"javascript:0").insertAfter("body")[0].contentWindow;h.onpropertychange=function(){try{if(event.propertyName==="title"){q.document.title=h.title}}catch(s){}}}};j.stop=k;o=function(){return a(q.location.href)};l=function(v,s){var u=q.document,t=$.fn[c].domain;if(v!==s){u.title=h.title;u.open();t&&u.write('<script>document.domain="'+t+'"<\/script>');u.close();q.location.hash=v}}})();return j})()})(jQuery,this);
jQuery.cookie = function(name, value, options) {
if (typeof value != 'undefined') { // name and value given, set cookie
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(); // use expires attribute, max-age is not supported by IE
}
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 { // only name given, get cookie
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;
}
};
(function($) {
$.toJSON = function(o)
{
if (typeof(JSON) == 'object' && JSON.stringify)
return JSON.stringify(o);
var type = typeof(o);
if (o === null)
return "null";
if (type == "undefined")
return undefined;
if (type == "number" || type == "boolean")
return o + "";
if (type == "string")
return $.quoteString(o);
if (type == 'object')
{
if (typeof o.toJSON == "function")
return $.toJSON( o.toJSON() );
if (o.constructor === Date)
{
var month = o.getUTCMonth() + 1;
if (month < 10) month = '0' + month;
var day = o.getUTCDate();
if (day < 10) day = '0' + day;
var year = o.getUTCFullYear();
var hours = o.getUTCHours();
if (hours < 10) hours = '0' + hours;
var minutes = o.getUTCMinutes();
if (minutes < 10) minutes = '0' + minutes;
var seconds = o.getUTCSeconds();
if (seconds < 10) seconds = '0' + seconds;
var milli = o.getUTCMilliseconds();
if (milli < 100) milli = '0' + milli;
if (milli < 10) milli = '0' + milli;
return '"' + year + '-' + month + '-' + day + 'T' +
hours + ':' + minutes + ':' + seconds +
'.' + milli + 'Z"';
}
if (o.constructor === Array)
{
var ret = [];
for (var i = 0; i < o.length; i++)
ret.push( $.toJSON(o[i]) || "null" );
return "[" + ret.join(",") + "]";
}
var pairs = [];
for (var k in o) {
var name;
var type = typeof k;
if (type == "number")
name = '"' + k + '"';
else if (type == "string")
name = $.quoteString(k);
else
continue;  //skip non-string or number keys
if (typeof o[k] == "function")
continue;  //skip pairs where the value is a function.
var val = $.toJSON(o[k]);
pairs.push(name + ":" + val);
}
return "{" + pairs.join(", ") + "}";
}
};
$.evalJSON = function(src)
{
if (typeof(JSON) == 'object' && JSON.parse)
return JSON.parse(src);
return eval("(" + src + ")");
};
$.secureEvalJSON = function(src)
{
if (typeof(JSON) == 'object' && JSON.parse)
return JSON.parse(src);
var filtered = src;
filtered = filtered.replace(/\\["\\\/bfnrtu]/g, '@');
filtered = filtered.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, ']');
filtered = filtered.replace(/(?:^|:|,)(?:\s*\[)+/g, '');
if (/^[\],:{}\s]*$/.test(filtered))
return eval("(" + src + ")");
else
throw new SyntaxError("Error parsing JSON, source is not valid.");
};
$.quoteString = function(string)
{
if (string.match(_escapeable))
{
return '"' + string.replace(_escapeable, function (a)
{
var c = _meta[a];
if (typeof c === 'string') return c;
c = a.charCodeAt();
return '\\u00' + Math.floor(c / 16).toString(16) + (c % 16).toString(16);
}) + '"';
}
return '"' + string + '"';
};
var _escapeable = /["\\\x00-\x1f\x7f-\x9f]/g;
var _meta = {
'\b': '\\b',
'\t': '\\t',
'\n': '\\n',
'\f': '\\f',
'\r': '\\r',
'"' : '\\"',
'\\': '\\\\'
};
})(jQuery);
jQuery.fn.doOnce = function(func){
this.length && func.apply(this);
return this;
}
Array.max = function( array ){
return Math.max.apply( Math, array );
};
var addthis_config = {
ui_language: 'no'
};
$.tools.dateinput.localize("no",  {
months:        'Januar, Februar, Mars, April, Mai, Juni, Juli, August, September, Oktober, November, Desember',
shortMonths:   'jan, feb, mar, apr, mai, jun, jul, aug, sep, okt, nov, des',
days:          'søndag, mandag, tirsdag, onsdag, torsdag, fredag, lørdag',
shortDays:     'søn, man, tir, ons, tor, fre, lør'
});
$.tools.validator.localize("no", {
'*'          : 'Ugyldig verdi',
':email'     : 'Du må oppgi en gyldig epostadresse',
':number'    : 'Du må oppgi et gyldig tall',
':url'       : 'Du må oppgi en gyldig URL',
'[max]'      : 'Du må oppgi en verdi mindre enn $1',
'[min]'      : 'Du må oppgi en verdi større enn $1',
'[required]' : 'Dette feltet er påkrevet'
});
$.tools.validator.addEffect("wall", function(errors, event) {
var wall = $(this.getConf().container).fadeIn();
wall.find("p").remove();
$.each(errors, function(index, error) {
wall.append(
"<p><strong>" + error.input.prev('label').text() + ":</strong> " + error.messages[0] + "</p>"
);
error.input.addClass('error');
});
}, function(inputs)  {
inputs.each(function(){
$(this).removeClass('error');
});
});
$(document).ready(function() {
$(":date").dateinput({
lang: 'no',
trigger: true,
format: 'dd.mm.yy',
firstDay: 1,
min: -1
});
skibygg.init();
$('.productThumb a').hover(function(){
$(this).find('.details').fadeTo('fast',0.1);
},function(){
$(this).find('.details').fadeOut('fast');
});
$('.basketRemoveItem').click(function(e){
e.preventDefault();
skibygg.activateBasketRemoveItem($(this).val());
});
$('.basketUpdateItem').click(function(e){
e.preventDefault();
cid = $(this).val();
count = $('#line_count_' + cid).val();
if (isNaN( count )) {
alert( "feil input" );
} else {
skibygg.activateBasketUpdateItem(cid, count);
}
});
$('#sortBy').change(function(e){
window.location.href = document.getElementById("sortBy").value;
});
$('#perPage').change(function(e){
window.location.href = document.getElementById("perPage").value;
});
if ( $('.productFull, .zoom, .simple_overlay').length > 2 ) {
$('.zoom').overlay({
target: '.simple_overlay'
});
}
if ( $('.productFull').length ) {
$('.tabs').each(function() {
new skibygg.Tabs($(this), {
autoPlay: false
});
});
$('#unit').change(function ( event ) {
var selected = $(this).find('option[value="' + $(this).val() + '"]').text(),
content = selected.split('/'),
priceTxt = $(this).closest('.price').find('span');
priceTxt.html(content[0] + '<small> /' + content[1] + '</small>');
});
$('#unit').trigger('change');
$('.productFull .thumbs a').click(function ( event ) {
var thumb = $(this);
thumb.addClass('selected');
thumb.siblings().removeClass('selected');
var productImage = thumb.parent().prev().find('img');
var overlayImage = $('.simple_overlay img');
var largestImageAvailable = thumb.data('original') || thumb.attr('href');
productImage.attr('src', thumb.attr('href'));
overlayImage.attr('src', largestImageAvailable);
return false;
});
}
if ( $("#searchResults").length ) {
}
$('.toggleButton a').click(function ( event ) {
var item = $(this).closest('li'),
container = $('.listView, .fourGrid'),
view = item.is('.list') ? 'listView' : 'fourGrid';
container.attr('className', view);
item.add(item.siblings()).toggleClass('active');
return false;
});
if ( $('#checkout').length ) {
if ( $('#shippingArea').length ) {
skibygg.initCheckout();
}
if ( $('#addressBook').length ) {
var container = $('#addressBook'),
addressBook = new skibygg.AddressBook(container),
form = container.closest('form'),
hiddenField = $("#selectedAddress");
container.bind('tabs.changed', function (e, active) {
var id = active.attr('id');
hiddenField.val(id);
});
$('input[name="deliveryType"]').change(function() {
var visibility = this.id == 'deliveryTypeShipping' ? 'show' : 'hide';
addressBook[visibility]();
});
}
}
});
var skibygg = {
init: function() {
skibygg.initSubNav();
skibygg.addMaps();
skibygg.activatePromotionImages();
skibygg.initRentalTools();
skibygg.activateFaq();
skibygg.alphaFilter();
skibygg.categoryFilter();
skibygg.equalizeCols();
skibygg.activateFaqForm();
skibygg.activateActivityForm();
skibygg.activateKitchenForm();
skibygg.initCoffeeBar();
skibygg.initAllProductsNav();
skibygg.setVariances(-1);
skibygg.initShoppingCartDetails();
skibygg.activateTabs();
},
initSubNav : function () {
var nav = $('#subNav');
if ( nav.length ) {
var sections = nav.find('.hasChildren');
sections.find('a').click(function ( evt ) {
evt.stopPropagation();
});
sections.click(function ( evt ) {
var target = $(this);
if ( target.is('li') ) {
$(this).toggleClass('open');
}
});
}
},
alphaFilter: function(){
skibygg.createFilter({
filterSelector: '.alphaFilter',
itemSelector: '.vcard',
dataKey: 'alpha',
paginationSelector: '.pagination li',
allData: 'all',
selectedClass: 'selected',
eventType: 'click',
hiddenBy: 'hiddenBy',
isSelect: false,
enableHistory: false
});
},
categoryFilter: function(){
skibygg.createFilter({
filterSelector: '.categoryFilter',
itemSelector: '.vcard',
dataKey: 'category',
paginationSelector: 'select#filterEmployees',
allData: 'all',
selectedClass: 'selected',
eventType: 'change',
hiddenBy: 'hiddenBy',
isSelect: true,
enableHistory: true
});
},
activateFaqForm: function() {
$("#faqForm").validator({
lang: 'no',
effect: 'wall',
container: '#faqFormErrors',
onSuccess: function(){
var form = $("#faqForm");
var data = {
objectID: 41091,
formData: form.serializeArray()
};
$.each( data.formData, function(){
var label = $('input[name=' + this.name + '], textarea[name=' + this.name + ']').prev('label');
this.label = label.text();
});
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::mailform',
data: data,
beforeSend: function(){
$('#faqForm .content').html( '<div class="waitspinner"></div>' );
},
success: function (html) {
$('#faqForm .content').html( '<div class="ps xmltext">' + html + '</div>');
},
error: function (xhr, txtStatus, error) {
}
});
return false;
}
});
},
activateActivityForm: function() {
$("#activityForm").validator({
lang: 'no',
effect: 'wall',
container: '#activityFormErrors',
onSuccess: function(){
var form = $("#activityForm");
var data = {
objectID: form.data('objectId'),
formData: form.serializeArray()
};
$.each( data.formData, function(){
var label = $('input[name=' + this.name + '], textarea[name=' + this.name + ']').prev('label');
this.label = label.text();
});
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::mailform',
data: data,
beforeSend: function(){
$('#activityForm .content').html( '<div class="waitspinner"></div>' );
},
success: function (html) {
$('#activityForm .content').html( '<div class="ps xmltext">' + html + '</div>');
},
error: function (xhr, txtStatus, error) {
}
});
return false;
}
});
},
activateKitchenForm: function() {
$("#kitchenForm").validator({
lang: 'no',
effect: 'wall',
container: '#kitchenFormErrors'
}).submit(function ( event ) {
if ( !event.isDefaultPrevented() ) {
event.preventDefault();
var form = $("#kitchenForm");
var data = {
objectID: 41106,
formData: form.serializeArray()
};
$.each( data.formData, function(){
var label = $('input[name=' + this.name + '], textarea[name=' + this.name + ']').prev('label');
this.label = label.text();
});
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::mailform',
data: data,
beforeSend: function(){
$('#kitchenForm .content').html( '<div class="waitspinner"></div>' );
},
success: function (html) {
$('#kitchenForm .content').html( '<div class="ps xmltext">' + html + '</div>');
},
error: function (xhr, txtStatus, error) {
}
});
}
});
},
createFilter: function(config){
$(config.filterSelector).each(function(){
var filter = $(this);
var filterItems = filter.find(config.itemSelector);
var clearFilter = function(){
filterItems.each(function(){
var hiddenBy = $(this).data(config.hiddenBy) || {};
hiddenBy[config.dataKey] = false;
var hideItem = false;
for( var i in hiddenBy ) {
if( hiddenBy[i] ) {
hideItem = true;
}
}
if( hideItem ) {
$(this).hide();
} else {
$(this).show();
}
});
}
var setFilter = function(data){
filterItems.each(function(){
var dataKey = $(this).data(config.dataKey);
var hiddenBy = $(this).data(config.hiddenBy) || {};
if ( dataKey === data ) {
hiddenBy[config.dataKey] = false;
} else {
hiddenBy[config.dataKey] = true;
}
var hideItem = false;
for( var i in hiddenBy ) {
if( hiddenBy[i] ) {
hideItem = true;
}
}
if( hideItem ) {
$(this).hide();
} else {
$(this).show();
}
$(this).data( config.hiddenBy, hiddenBy );
});
}
filter.find( config.paginationSelector ).bind( config.eventType, function(){
if( config.isSelect ) {
var data = $(this).find('option:selected').data(config.dataKey);
} else {
var data = $(this).data(config.dataKey);
}
if( data === config.allData ) {
clearFilter();
$(this).siblings().removeClass(config.selectedClass);
} else {
setFilter(data);
$(this).siblings().removeClass(config.selectedClass);
$(this).addClass(config.selectedClass);
}
if( config.enableHistory ) {
if( config.isSelect ) {
var hash = $(this).find('option:selected').data('hash');
} else {
var hash = $(this).data('hash');
}
if( !hash ) {
hash = '';
}
window.location.hash = hash;
}
});
if( config.enableHistory && window.location.hash ) {
if( config.isSelect ) {
var options = $(this).find('option');
options.each(function(){
if( '#' + $(this).data('hash') === window.location.hash ) {
$(this).attr( 'selected', 'selected' );
filter.find( config.paginationSelector ).trigger( config.eventType );
}
});
} else {
var hash = $(this).data('hash');
}
};
});
},
activateFaqVotingButtons: function(){
var voteData = $.cookie('faqVoteData');
voteData = $.parseJSON(voteData) || {};
$('.faq .vote').each(function(){
var voteEl = $(this);
var objectID = $(this).data('objectID');
if( voteData[objectID] ) {
voteEl.addClass('disabled');
} else {
$(this).find('a').click( function(){
var vote = $(this).data('vote');
if( ( vote === 'up' || vote === 'down' ) && /^\d+$/.test( objectID ) ) {
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::voteFaq',
data: {
vote: vote,
objectID: objectID
},
success: function( html ) {
voteEl.addClass('disabled');
voteData[objectID] = 1;
console.log( voteData );
$.cookie('faqVoteData', $.toJSON(voteData));
},
error: function( xhr, txtStatus, error ) {
}
});
}
});
}
});
},
activateFaq: function(){
skibygg.activateFaqVotingButtons();
$('.faq li h3').click(function(){
$(this).next('.answer').slideToggle('fast');
$(this).toggleClass('expanded');
});
},
initNotifiers: function() {
skibygg.notifiers = {
'rentTool' : new skibygg.Notifier({
title: $('.pageTitle').text(),
msg: 'er lagt i handlevognen'
})
};
$('body').delegate('button.notify', 'click', function(e) {
var notifier = skibygg.notifiers[this.id];
if ( notifier ) {
for (var n in skibygg.notifiers) if ( skibygg.notifiers.hasOwnProperty(n) ) {
skibygg.notifiers[n].hide();
}
notifier.execute.call(skibygg.notifiers[this.id], $(this));
}
return false;
});
},
setVariances: function() {
var varList = "";
var artNr = $('#articleNr').text();
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::getVariances',
data: {
artNo: artNr
},
success: function( html ) {
varList = $.parseJSON( html );
},
error: function( xhr, txtStatus, error ) {
}
});
function handleVarChange() {
var varNum = parseInt( $(this).attr('id').replace( 'variant_', '' ) );
var newID = updateVarChange(varNum);
if ( newID ) {
var hasVariance = new RegExp("varians"),
url = window.location.href;
if ( hasVariance.test(url) ) {
url = url.split("/(varians)")[0];
}
url += "/(varians)/" + newID;
window.location = url;
}
}
function updateVarChange(num) {
if ( num == -1 ) {
$('#variant_0').append( new Option( "Velg " + varList['variance_types'][0], -1 ) );
for ( var key in varList['variance_list'] ) {
$('#variant_0').append( new Option( key.split(";")[1], key.split(";")[1] ) );
}
return false;
} else if ( num == 0 ) {
if ( varList['variance_types'].length > 1 ) {
$('#variant_1').empty();
$('#variant_1').append( new Option( "Velg", -1 ) );
for ( var key in varList['variance_list'][varList['variance_types'][0] + ";" + $('#variant_0').val()] ) {
$('#variant_1').append( new Option( key.split(";")[1], key.split(";")[1] ) );
}
return false;
} else {
return varList['variance_list'][varList['variance_types'][0] + ";" + $('#variant_0').val()];
}
} else if ( num == 1 ) {
return varList['variance_list'][varList['variance_types'][0] + ";" + $('#variant_0').val()][varList['variance_types'][1] + ";" + $('#variant_1').val()];
}
}
$(".variance").each(function() {
$(this).bind('change', handleVarChange);
});
},
initCheckout: function() {
var shipping = new skibygg.Shipping(),
cachedPostalCode = "",
container = $('#shippingArea');
function handleInteraction(e) {
e.preventDefault();
var value = $('#postalCode').val(),
postalCode;
if ( value === cachedPostalCode ) {
return;
}
postalCode = new skibygg.PostalCode( value );
if ( postalCode.isValid() ) {
cachedPostalCode = postalCode.getValue();
container.addClass('loading').find('#result').empty();
shipping.estimatePrice(cachedPostalCode, function ( result ) {
container.removeClass('loading');
container.find('#result').empty().append( result );
});
}
}
$('#checkPrice').removeClass('hidden').bind('click', handleInteraction);
$('#postalCode').bind('keyup', handleInteraction);
container.show();
},
initCoffeeBar: function() {
if ( $('#coffeeBar').length ) {
var coffeeBar = new CoffeeBar();
}
},
initRentalTools: function() {
if ( $('#rentTools').length ) {
var rentalTools = new RentalTools();
}
},
addMaps: function() {
$('.map').each(function(){
var bounds = new google.maps.LatLngBounds();
var Latlngs = new Array();
var locations = $(this).find('.maplocation');
var lat    = parseFloat(locations.find('.latitude').text());
var lng    = parseFloat(locations.find('.longitude').text());
var myLatlng = new google.maps.LatLng(lat,lng);
var myOptions = {
zoom: 13,
center: myLatlng,
mapTypeId: google.maps.MapTypeId.ROADMAP,
scrollwheel: false
}
var map = new google.maps.Map($(this).find('.mapCanvas').get(0), myOptions);
var infowindow = new google.maps.InfoWindow({});
google.maps.event.addListener(map, 'click', function() {
infowindow.close();
});
locations.each(function(){
var location = $(this);
var lat      = parseFloat(location.find('.latitude').text());
var lng      = parseFloat(location.find('.longitude').text());
var content  = location.find('.content').html();
var myLatlng = new google.maps.LatLng(lat,lng);
var icon     = '/extension/skibygg/design/skibygg/images/' + ($('.map').closest('.frontpageMap').length ? 'officePin.png' : 'pin.png');
Latlngs.push(myLatlng);
var marker   = new google.maps.Marker({
position: myLatlng,
map: map,
title: location.find('.title').text(),
icon: icon
});
google.maps.event.addListener(marker, 'click', function() {
infowindow.close();
var info = $("<div/>").html(content);
infowindow.setContent(info.get(0));
infowindow.open(map,marker);
});
});
if( locations.length > 1 ) {
for( i = 0; i < Latlngs.length; i++ ) {
bounds.extend(Latlngs[i]);
}
map.fitBounds(bounds);
}
});
},
activatePromotionImages: function() {
$('.panoramaBanner').each(function() {
new skibygg.Tabs($(this), {
autoPlay: true,
cycleInterval: 4000
});
});
},
supply: function( tplStr, data ) {
for( var prop in data ) {
tplStr = tplStr.split("{"+prop+"}").join(data[prop]);
}
return tplStr;
},
equalizeCols: function(){
$(".line").each( function() {
var maxHeight = 0;
$(this).find('> .unit > .lineRightBox').each(function(){
var height = this.offsetHeight;
$(this).css( 'padding-bottom', 0 );
if ( height > maxHeight ) {
maxHeight = height;
}
}).each(function(){
var height = this.offsetHeight;
var gap = maxHeight - height;
if ( gap > 0 ) {
$(this).css('padding-bottom', gap + 'px' )
}
});
});
},
activateBasketRemoveItem: function(removeID){
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::updateBasketRemove',
data: {
removeID: removeID
},
success: function( html ) {
var els = html.split( ';', 2 );
if (els[0] == 1) {
$('#line_' + removeID).remove();
$('#total_price').text(els[1]);
}
},
error: function( xhr, txtStatus, error ) {
}
});
},
activateBasketUpdateItem: function(updateID, count){
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::updateBasketQuantity',
data: {
updateID: updateID,
count: count
},
success: function( html ) {
var els = html.split( ';', 3 );
if (els[0] == 1) {
if (count == 0) {
$('#line_' + updateID).remove();
} else {
$('#sum_line_' + updateID).text(els[1]);
}
$('#total_price').text(els[2]);
}
},
error: function( xhr, txtStatus, error ) {
}
});
},
initAllProductsNav : function () {
var templates = {
productNav : "<div id='allProducts'><ul>{categories}</ul></div>",
categories : "<li><h3><a href='{url}' class='clearfix'>{megaThumb}<span>{title}</span></a></h3><ul>{children}{overflow}<li><a href='{url}'>» Alle produkter</a></li></ul></li>",
children   : "<li><a href='{url}'>{subCategoryTitle}</a></li>"
};
$.ajax({
type: "GET",
url: $.ez.root_url + 'ezjscore/call/skibygg::getProductCategories',
dataType: 'json',
success: function ( response ) {
var productNav = buildHtml($.parseJSON(response.content));
productNav = bindHandlers($(productNav));
correctColumns(productNav);
var link = $('<a href="/produkter" id="showAllProducts">Se alle produktkategorier</a>');
productNav.append(link);
$('#mainNav').after( productNav );
},
error: function (xhr, txtStatus, error) {
console.log(xhr, txtStatus, error);
}
});
function buildHtml ( json ) {
var productCategories = json,
categories = "",
productNav = "";
for ( var category in productCategories ) {
var item = productCategories[category],
children = "";
for ( var sub in item.children ) {
children += skibygg.supply(templates.children, {
subCategoryTitle: item.children[sub].title,
url: item.children[sub].url
});
}
categories += skibygg.supply(templates.categories, {
title: item.title,
url: item.url,
megaThumb: ( item.image ) ? "<img src=" + item.image.image.megamenuthumbnail + " width='40' height='40' />" : '',
children: children,
overflow: item.children.length == 5 ? "<li>...</li>" : ""
});
}
return skibygg.supply(templates.productNav, {
categories: categories
});
}
function correctColumns ( nav ) {
var listItems = nav.children('ul').children('li');
listItems.each(function ( i, elem ) {
if ( i % 5 == 0 ) {
$(elem).css({
borderLeft: 'none',
width: 191,
clear: 'left'
});
}
});
}
function bindHandlers ( nav ) {
var mainNav = $('#mainNav'),
link = mainNav.find('a[href="/produkter"]').attr('id', 'productBtn'),
productsMenuItem = link.closest('li');
nav.css({
top: mainNav.position().top + mainNav.height()
}).hide();
link.click(function ( event ) {
nav.slideToggle('fast');
productsMenuItem.toggleClass('active');
return false;
});
$(document).click(function ( event ) {
if ( !$(event.target).is('#allProducts, #allProducts *, #productBtn') ) {
productsMenuItem.removeClass('active');
nav.slideUp('fast');
}
});
return nav;
}
},
initShoppingCartDetails : function () {
$("#shoppingCart").delegate("tr", "hover", handler, handler);
function handler ( event ) {
toggleVarianceDetails( $(this).find('.variance') );
}
function toggleVarianceDetails ( details ) {
if ( details.length ) {
var value = details.is(":visible") ? 'none' : 'block';
details.css({ display: value });
}
}
},
activateTabs: function(){
$("ul.tabs").tabs("div.panes > div");
}
};
skibygg = skibygg || {};
skibygg.Tabs = function Tabs(o, options) {
this.options = $.extend({
autoPlay: false,
cycleInterval: 4500,
autoWidth: true,
panesClass: 'content'
}, options);
this.currentIndex = null;
this.initialize(o, o.find('.' + this.options.panesClass));
o.addClass('initialized');
}
skibygg.Tabs.prototype = {
initialize: function(container, sections) {
var that = this,
heights = [],
nav = this.createNav(sections),
links = nav.find('a');
container.prepend(nav);
links.click(function(e) {
that.handleInteraction.apply(
that, [this, sections, links]
);
return false;
});
if ( this.options.autoWidth ) {
this.distributeWidth(
container.outerWidth(),
links.length,
container.find('li, li > a')
);
}
sections.hide();
links.first().addClass('first').click();
if ( this.options.autoPlay ) {
var nextUp = 0,
timer = null;
links.closest('.tabs').bind('tabs.changed', function ( event ) {
clearInterval(timer);
});
timer = setInterval(function () {
if ( ++nextUp === links.length ) {
nextUp = 0;
}
that.handleInteraction.apply(
that, [links.eq(nextUp), sections, links, true]
);
}, this.options.cycleInterval);
}
},
distributeWidth: function(totalWidth, numOfLinks, elems) {
var padding = 0;
elems.each(function(i, elem) {
padding = parseInt($(elem).css('paddingLeft'), 10) * 2;
$(elem).css({
width: totalWidth / numOfLinks - padding
});
});
},
createNav: function(sections) {
var navItemTemplate = '<li><span></span><a href="#">{title}</a></li>',
nav = $('<ul class="navigation"></ul>');
sections.each(function() {
title = $(this).find('h3:first');
nav.append(
skibygg.supply(navItemTemplate, {
title: title.text()
})
);
title.remove();
});
return nav;
},
changeSection: function(sections, links, index, auto) {
var newSection = sections.eq(index),
h = Array.max([
newSection.outerHeight(),
links.closest('ul').outerHeight()
]);
if ( auto === undefined ) auto = false;
sections.eq(this.currentIndex).hide();
newSection.parent().height(h);
newSection.fadeIn();
links.parent('li').removeClass('active');
links.eq(index).parent().addClass('active');
if ( !auto ) {
links.closest('.initialized').trigger('tabs.changed', [newSection]);
}
},
handleInteraction: function(el, sections, links, auto) {
var i = ( links.index(el) == -1 ) ? 0 : links.index(el);
if( i !== this.currentIndex ) {
this.changeSection(sections, links, i, auto);
this.currentIndex = i;
}
}
};
skibygg = skibygg || {};
skibygg.Shipping = function Shipping() {
};
skibygg.Shipping.prototype = {
templates : {
error : "<div class='box'><p class='header'>{message}</p></div>",
success : "<div class='boxwrap ps'>" +
"<p class='header'>Estimert frakt til postnummer {postalCode} er <strong class='price'>" +
"{price},-</strong>.</p></div>"
},
estimatePrice : function ( postalCode, callback ) {
var that = this;
this.calculatePrice(postalCode, function success( price ) {
callback(that.decorateResult({
template: 'success',
data: {
postalCode: postalCode,
price: price
}
}));
}, function error(xhr, status, error) {
callback(that.decorateResult({
template: 'error',
data: {
message: status
}
}));
});
},
getPrice : function ( postalCode, callback ) {
this.calculatePrice( postalCode, function success( price ) {
callback(price);
});
},
calculatePrice : function ( postalCode, successCallback, errorCallback ) {
var timer = setTimeout(function () {
clearTimeout(timer);
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::getShippingPrice',
data: { 'zip': postalCode },
success: function (price) {
successCallback(price);
},
error: function (xhr, txtStatus, error) {
container.elem.removeClass('loading').children().show();
errorCallback(null);
}
});
}, 3000);
},
decorateResult : function (result) {
result = skibygg.supply(
this.templates[result.template],
result.data
);
return result;
}
};
skibygg.AddressBook = function AddressBook(container) {
var self = this,
cardTmpl = "<div id='{id}' class='content'>" +
"<h3 class='h3'>{title}</h3>" +
"<p>{streetAddress}</p>" +
"<p>{streetAddress2}</p>" +
"<p>{postalCode} {postalArea}</p>" +
"<p>Frakt kostnad for {postalCode}: " +
"<span id='price'><img src='/extension/skibygg/design/skibygg/images/loading.gif'/></span></p>" +
"</div>";
this.elem = container;
this.cards = {};
this.getCards(function ( cards ) {
if ( cards ) {
self.buildCardNavigation(cards, cardTmpl);
}
});
};
skibygg.AddressBook.prototype = {
show : function () {
this.elem.show();
},
hide : function () {
this.elem.hide();
},
getCards : function ( callback ) {
var container = this.elem;
container.addClass('loading').children().hide();
var userID = $('#UserID').val();
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::customerAddresses',
data: { 'customerId': userID },
dataType: 'json',
success: function (addresses) {
callback($.parseJSON(addresses.content));
},
error: function (xhr, txtStatus, error) {
container.elem.removeClass('loading').children().show();
callback(null);
}
});
},
buildCardNavigation : function ( cards, template ) {
var shipping = new skibygg.Shipping();
for ( var card in cards ) {
var addressCard = skibygg.supply(
template, cards[card]
);
var price = this.elem.prepend(addressCard).find('#price');
postalCode = new skibygg.PostalCode( cards[card].postalCode );
if ( postalCode.isValid() ) {
shipping.getPrice(postalCode.getValue(), function ( result ) {
price.html(result);
});
}
}
new skibygg.Tabs(this.elem, {
autoWidth: false
});
var addressId = $('#selectedAddress').val();
if ( addressId && addressId !== "" ) {
var selected    = document.getElementById(addressId),
addressBook = $('#addressBook'),
sections    = addressBook.find('.content'),
links       = addressBook.find('li a');
links.eq(sections.index(selected)).trigger('click');
}
this.elem.removeClass('loading');
}
};
skibygg.PostalCode = function PostalCode(str) {
this.value = str || "";
};
skibygg.PostalCode.prototype = {
isValid : function () {
return this.value.match(/^[0-9]{4}$/) !== null;
},
setValue : function (str) {
this.value = str;
},
getValue : function () {
return this.value;
}
};
function ShoppingItem(o) {
if ( !o || o.id === undefined ) {
throw "Trying to create an item with an invalid item id";
}
this.id = o.id;
this.price = o.price || 0;
this.quantity = o.quantity || 1;
this.name = o.name || "";
}
ShoppingItem.prototype = {
increaseQuantity : function ( num ) {
num = num || 1;
this.setQuantity(this.getQuantity() + num);
},
decreaseQuantity : function () {
this.setQuantity(this.getQuantity() - 1);
},
setQuantity : function ( quantity ) {
quantity = parseInt(quantity, 10);
this.quantity = (!isNaN(quantity) && quantity >= 0) ? quantity : 0;
},
getId : function () {
return this.id;
},
getPrice : function () {
return this.price;
},
getQuantity : function () {
return parseInt(this.quantity, 10);
},
getName : function () {
return this.name;
},
getData : function () {
return {
id: this.getId(),
name: this.getName(),
quantity: this.getQuantity(),
price: this.getPrice()
};
},
render : function ( showPrice ) {
var tpl = "<tr id='artNo-{id}'><td>{name}</td><td>{quantity} stk " +
"<nav><a href='#increase' class='increase'>+</a>" +
"<a href='#decrease' class='decrease'>-</a></nav></td>";
if ( showPrice ) {
tpl += "<td>{price},-</td>";
}
tpl += "</tr>";
return skibygg.supply( tpl, this.getData() );
}
};
function ShoppingCart(cookieName, showPrices) {
this.numberOfItems = 0;
this.items = {};
this.cookieName = cookieName || 'skiCart';
this.showPrices = (showPrices === undefined) ? true : showPrices;
}
ShoppingCart.prototype = {
load : function () {
var cartData = $.cookie(this.cookieName),
i, q, len, items, item;
if ( !cartData ) {
return;
}
items = $.parseJSON(cartData);
for ( i = 0, len = items.length; i < len; i++ ) {
item = new ShoppingItem({
id: items[i].id,
name: items[i].name,
price: items[i].price,
quantity: items[i].quantity
});
this.add(item);
}
},
save : function () {
var items = [];
for ( var id in this.items ) {
if ( this.items.hasOwnProperty(id) ) {
items.push(this.items[id].getData());
}
}
$.cookie(this.cookieName, $.toJSON(items));
},
getCartData : function() {
var cartData = $.cookie(this.cookieName);
if ( !cartData ) {
return;
}
return $.parseJSON(cartData);
},
empty : function () {
$.cookie( this.cookieName, false );
this.items = {};
this.numberOfItems = 0;
},
isEmpty : function () {
return this.numberOfItems === 0;
},
add : function (item) {
var q = (item.quantity && item.quantity > 1) ? item.quantity : 1;
if ( this.hasItem(item.id) ) {
this.items[item.id].increaseQuantity(q);
} else {
this.items[item.id] = item;
}
this.numberOfItems += q;
return item;
},
remove : function ( id ) {
if ( this.hasItem(id) ) {
var item = this.items[id];
if ( item.getQuantity() < 2 ) {
delete this.items[id];
}
item.decreaseQuantity();
this.numberOfItems --;
return item;
}
return null;
},
hasItem : function ( id ) {
return this.items[id] !== undefined;
},
getNumberOfItems : function () {
return this.numberOfItems;
},
render : function ( showPrices ) {
var html = "<table>",
total = 0,
itemId;
showPrices = arguments.length ? arguments[0] : true;
for ( itemId in this.items ) {
if ( this.items.hasOwnProperty(itemId) ) {
html += this.items[itemId].render(showPrices);
total += this.items[itemId].price * this.items[itemId].quantity;
}
}
if ( showPrices && this.numberOfItems > 0 ) {
html += "<tr class='total'><td colspan='2'>Totalpris:</td>" +
"<td class='numeric'>" + total + ",-</td></tr>";
}
html += "</table>";
return html;
}
};
function ShoppingCartGUI (cart, o) {
var self = this;
this.cart = cart;
this.container = o.container;
this.showPrices = ( o.showPrices === undefined ) ? true : o.showPrices;
$('.increase, .decrease', this.container).live('click', function(e) {
var btn = $(this),
articleNo = btn.closest('tr').attr('id').replace('artNo-', '');
if ( btn.hasClass('increase') ) {
self.cart.add(new ShoppingItem({ id: articleNo }));
}
if ( btn.hasClass('decrease') ) {
self.cart.remove(articleNo);
}
self.cart.save();
self.reflow();
return false;
});
$("form", this.container).validator({
lang: 'no',
effect: 'wall',
container: '#' + this.container.attr('id') + 'Errors'
}).submit(function ( event ) {
if ( !event.isDefaultPrevented() ) {
event.preventDefault();
self.sendOrder.call(self, o.objectID);
}
});
}
ShoppingCartGUI.prototype = {
reflow : function () {
var numOfItems = this.cart.getNumberOfItems(),
template = "",
heading = "";
if ( numOfItems === 1 ) {
template = "{totalItems} vare";
} else if ( numOfItems > 1 ) {
template = "{totalItems} varer";
} else {
template = 'Ingen varer';
}
heading = skibygg.supply(
template,
{ totalItems: numOfItems }
);
$('table', this.container).replaceWith(this.cart.render(this.showPrices));
$('h2 span', this.container).text(heading);
},
sendOrder : function ( objectID ) {
var self = this,
form = $("form", self.container),
data = {
objectID: objectID,
formData: form.serializeArray(),
cart: this.cart.getCartData()
};
$.each( data.formData, function () {
var label = $('input[name=' + this.name + '], textarea[name=' + this.name + ']').prev('label');
this.label = label.text();
});
$.ajax({
type: "POST",
url: $.ez.root_url + 'ezjscore/call/skibygg::mailform',
data: data,
beforeSend: function(){
var content = $('.content', self.container);
content.children().hide();
content.prepend( '<div class="waitspinner"></div>' );
},
success: function (html) {
self.showReceipt.call(self, html);
var content = $('.content', self.container);
content.find('.waitspinner').remove();
content.children().show();
form.get(0).reset();
},
error: function (xhr, txtStatus, error) {
self.showOrderFailure.call(self);
var content = $('.content', self.container);
content.find('.waitspinner').remove();
content.children().show();
}
});
},
showReceipt : function (html) {
this.cart.empty();
this.reflow();
var receipt = $('<div class="clearBox pl receipt">' + html + '</div>'),
close = $('<a href="#close" class="close">close</a>').click(function(e) {
$(this).parent().remove();
return false;
});
$('.content', this.container).prepend( receipt );
receipt.append( close );
},
showOrderFailure : function () {
var html = "<h2>Bestilling feilet</h2><p>Prøv igjen eller ta kontakt med oss:</p>" +
"<p><a href='post@skibygg.no'>post@skibygg.no</a></p><p>64 85 46 00</p>",
receipt = $('<div class="clearBox pl receipt">' + html + '</div>'),
close = $('<a href="#close" class="close">close</a>').click(function(e) {
$(this).parent().remove();
return false;
});
$('.content', this.container).prepend( receipt );
receipt.append( close );
}
};
function CoffeeBar () {
var self = this;
this.cart = new ShoppingCart('skiCoffeBar');
this.gui = new ShoppingCartGUI( this.cart, {
objectID: 20856,
container: $('#coffeeBar')
});
this.cart.load();
this.gui.reflow();
$('#coffeeBarMenu input[type="text"]').bind('keyup', function (e) {
if ( e.keyCode == '13' ) {
$(this).closest('td').next().find('button').trigger('click');
}
});
$('#coffeeBarMenu').delegate('button', 'click', function (e) {
var data = self.extractMenuItemInfo(this),
quantityInput = $(this).closest('td').prev().find('input[type="text"]'),
quantity = quantityInput.val();
if ( self.validateQuantity(quantity) ) {
data.quantity = parseInt(quantity, 10);
var menuItem = new ShoppingItem(data);
self.cart.add(menuItem);
self.cart.save();
self.gui.reflow();
quantityInput.val("").removeClass('error');
} else {
quantityInput.addClass('error');
}
return false;
});
}
CoffeeBar.prototype = {
extractMenuItemInfo: function (trigger) {
var row = $(trigger).closest('tr'),
data = {};
if ( row && row.length == 1 ) {
data = {
name : $.trim( row.find('td:first').text() ),
id : row.attr('id').replace('article-', ''),
price : this.parsePrice( row.find('.price').text() )
};
}
return data;
},
validateQuantity: function ( quantity ) {
return quantity && /^([1-9]+)([0-9]{0,2})$/.test(quantity);
},
parsePrice : function ( str ) {
return parseFloat(str.replace(/(?:kr\s{0,1})(\d?((\,){0,1}(\d))?)(?:\,\-){0,1}/i, "$1").replace(",","."));
}
};
function RentalTools () {
var self = this;
this.cart = new ShoppingCart('skiRentalTools');
this.gui = new ShoppingCartGUI(this.cart, {
objectID: 20849,
container: $('#rentTools'),
showPrices: false
});
this.cart.load();
this.gui.reflow();
$('#rentTool').bind('click', function (e) {
var data = self.extractProductDetailsData();
if( data !== null ) {
var tool = new ShoppingItem(data);
self.cart.add(tool);
self.cart.save();
self.gui.reflow();
}
});
}
RentalTools.prototype = {
extractProductDetailsData: function () {
var productData = null;
if ( $('.productFull').length ) {
productData = {
name : $.trim($('.pageTitle').text()),
id : $.trim($('#articleNr').text()),
price : parseInt($.trim($('.specification .price h1:first span').text().replace('kr ', '')), 10)
}
}
return productData;
}
};
skibygg.Notifier = function(content) {
this.elem = this.create(skibygg.supply(
"<div class='notifier'><h1>{title}</h1><p>{msg}</p></div>",
content
));
var self = this;
fluff = parseInt(this.elem.outerWidth(), 10) - parseInt(this.elem.width(), 10);
};
skibygg.Notifier.prototype = {
create: function(html) {
return $(html).appendTo('body');
},
execute: function(button) {
this.show(
button.offset(),
button.outerWidth() - fluff,
this.elem
);
},
show: function(o, w, elem) {
if (this.timer) clearTimeout(this.timer);
elem.css({ display: 'block', width: w })
.offset({
left: o.left,
top: o.top - elem.outerHeight()
});
this.timer = setTimeout(function() {
elem.fadeOut();
}, 2000);
},
hide: function() {
this.elem.hide();
}
};

