﻿var featureSliderAutoScrollMiliseconds = 8000;
$(document).ready(function () {
    $('link[href="/umbraco/plugins/umbracoContour/css/defaultform.css"]').remove();
    wizard();
    addLastChildTest();
    $('.siteFooter .formNewsletter').prepareFormFieldsLabelInside();
    $('.boxFinancing').prepareFormFieldsLabelInside();
    $('.colText .cmd .btnFinancing').click(function (event) { event.preventDefault(); if ($('.boxFinancing:visible').size() == 0) { $('html').scrollTop($('.tblSpecs').offset().top - 90); } $('.boxFinancing').slideToggle(); });


    if ($('.lastchild').size() == 0) {
        $('header .basket dl:last-child dd').addClass('lastChild');
        $('header .mainNavigation li:last-child a').addClass('lastChild');
        $('.content p:last-child').addClass('lastChild');
        $('.tblCompare tr:nth-child(odd)').addClass('nthChildOdd');
        $('.findStoreList .storeListHolder tr:nth-child(odd)').addClass('nthChildOdd');
        $('.findStoreList .storeListHolder td:nth-child(2), .findStoreList .storeListHolder th:nth-child(2)').addClass('nthChild2');
        $('.productHolder .colImage .listThumbs li:nth-child(odd)').addClass('nthChildOdd');
    }

    $('#hideSpecs').click(function (event) { event.preventDefault(); $(this).toggleClass('showSpecs'); $('.tblBasket tr:not(.rowSum)').toggle(); $('.listAddresses').slideToggle(); });

    $("#productSliderTopOffers .carouselHolder").tallestInCarousel();
    $("#productSliderTopOffers .carouselHolder").jCarouselLite({
        //auto: 1800,
        speed: 500,
        btnNext: "#productSliderTopOffers .carousel .next",
        btnPrev: "#productSliderTopOffers .carousel .prev",
        visible: 4
    });

    $("#productSliderPopularProducts .carouselHolder").tallestInCarousel();
    $("#productSliderPopularProducts .carouselHolder").jCarouselLite({
        //auto: 1800,
        speed: 500,
        btnNext: "#productSliderPopularProducts .carousel .next",
        btnPrev: "#productSliderPopularProducts .carousel .prev",
        visible: 4
    });

    $('.btnSubmit').click(function (event) {
        if ($(this).attr('id') != 'searchStoreSubmit') {
            event.preventDefault();
            $(this).closest('form').submit();
        }
    });

    if ($('.tblCompare').size() > 0)
        formatCompareTable();

    /**
    * MENU OPTIONS (default values in parenthesis)
    * ------------
    * div:        Where the slide-menu will go. ("#menu-container")
    * controls:   Where are the controls for the menu. ("#menu-controls")
    * loader:     If you are using a loading graphic, the menu will hide it for you once loaded. If not,
    *               set it to 'false' or ''. (false)
    * x:          Total width of list item including margins and padding in px. (150)
    * y:          Total height of list item including margins and padding in px. (150)
    * start:      Index of <ul> to open first. (0)
    * speed:      Speed of all animations in ms . (300)
    * delay:      Delay between list item animations when transitioning in ms. (60)
    * easing:     Type of easing to use for list item animations, use '' for no easing effect. ('')
    *               FYI - "easeOutBackSmall" is a custom addition I made for this demo, it is not included in the
    *               standard set of easing animations.
    * easeIn:     Type of easing to use for initial drop-in animation, use '' for none. ('')
    *               This demo includes the jQuery easing plugin: http://gsgd.co.uk/sandbox/jquery/easing/
    *               Supported easing methods in the plugin are listed and demoed at the above url.
    * preloadAll: Wait for all menu images to load before animating in, or just the first set? (false)
    *               By default, with this set to false, the menu will wait until all images in the first menu set are
    *               loaded before the beginning animation is fired. If set to true, it will wait for all menu images to load.
    */

    var options = {
        div: "#sliderMenuHolder",
        controls: "#sliderMenuControls",
        loader: "#loadingSliderMenu",
        x: 120,
        y: 200, /*is not in use in the novicell version; is taken automatically from the image height attributes*/
        easing: "easeOutBackSmall",
        easeIn: "easeOutBack",
        preloadAll: true
    };

    var menu = new slideMenu(options);

    $("a[rel=productGalleryGroup]").fancybox({
        'overlayShow': false,
        'transitionIn': 'elastic',
        'transitionOut': 'elastic',
        'opacity': true,
        'titlePosition': 'inside'
    });
    $('.productHolder .colImage .listThumbs li:nth-child(odd)').each(function () {
        if ($(this).height() > $(this).next().height())
            $(this).next().height($(this).height())
        else
            $(this).height($(this).next().height())
    });

    //Hide navigation if empty
    var textPageNavigation = $('.textPage .navigationSub');
    if (textPageNavigation.length > 0) {
        if (textPageNavigation.find('li').length == 0) {
            textPageNavigation.hide();
            $('.textPage .content').addClass('contentNoNav');
        }
    }
});


function addLastChildTest()
{
	// :last-child pseudo selector test.
	// By @laustdeleuran and @emilchristensen
	// Please see http://reference.sitepoint.com/css/pseudoclass-lastchild for weird :last-child behaviour in FireFox below 2.0 and Safari below 2.0.
	// Original Modernizr test here: http://jsfiddle.net/laustdeleuran/3rEVe/ and Pure JS here: http://jsfiddle.net/laustdeleuran/hvZ3J/

	Modernizr.addTest('lastchild', function () {
	    var hasLastChild,
	        rules = ['#modernizr-last-child li{display:block;width:100px;height:100px;}','#modernizr-last-child li:last-child{width:200px;}'],
	        head = document.getElementsByTagName('head')[0] || (function () {
	            return document.documentElement.appendChild(document.createElement('head'));
	        }()),
	        root = document.body || (function () {
	            return document.documentElement.appendChild(document.createElement('body'));
	        }()),
	        list = document.createElement('ul'),
	        firstChild = document.createElement('li'),
	        lastChild = document.createElement('li'),
	        style = document.createElement('style');

	    style.type = "text/css";
	    if(style.styleSheet){ style.styleSheet.cssText = rules.join(''); }
	    else {style.appendChild(document.createTextNode(rules.join(''))); }
	    head.appendChild(style);

	    list.id = "modernizr-last-child";
	    list.appendChild(firstChild);
	    list.appendChild(lastChild);
	    root.appendChild(list);
	    hasLastChild = lastChild.offsetWidth > firstChild.offsetWidth;

	    head.removeChild(style);
	    root.removeChild(list);

	    return hasLastChild;
	});

}




(function($) {                                          // Compliant with jquery.noConflict()
	$.fn.tallestInCarousel = function(o) {
	    return this.each(function() {
	    	var tallestImg=0;
				$(this).find('li .img img').each(function(index){
					if($(this).attr('height')*1 > tallestImg)
						tallestImg = $(this).attr('height')*1;
				});
				$(this).find('li .img').css('height',tallestImg+'px');
				$(this).find('li').css('height','auto');

				var tallestName=0;
				$(this).find('li .cntName').each(function(){
					if($(this).height()*1 > tallestName)
						tallestName = $(this).height()*1;
				});
				$(this).find('li .cntName').css('height',tallestName+'px');
	    });
	};
})(jQuery);




(function($) {                                          // Compliant with jquery.noConflict()
$.fn.prepareFormFieldsLabelInside = function(o) {
    o = $.extend({
        textfield: true,
        textarea: true,
        password: true
    }, o || {});

    return this.each(function() {                           // Returns the element collection. Chainable.


        if(o.textfield)
            doTextfield($(this))

        if(o.textarea)
            doTextarea($(this))

        if(o.password)
            doPassword($(this))

        function doTextfield(objFieldAncestor) {
        	$(objFieldAncestor).find('input[type=text][title]').focus(function () { showHideInputValue($(this), 'focus') }).blur(function () { showHideInputValue($(this), 'blur') }).each(function () { showHideInputValue($(this), 'blur') });
        };

        function doTextarea(objFieldAncestor) {
        	$(objFieldAncestor).find('textarea[title]').focus(function () { showHideInputValue($(this), 'focus') }).blur(function () { showHideInputValue($(this), 'blur') }).each(function () { showHideInputValue($(this), 'blur') });
        };

        function doPassword(objFieldAncestor) {
        	$(objFieldAncestor).find('input[type=password][title]').focus(function () {showHidePasswordLabel($(this), 'focus')}).blur(function () {showHidePasswordLabel($(this), 'blur')}).each(function () {$(this).wrap('<label for="'+$(this).attr('id')+'"></label>');$(this).before('<span>'+$(this).attr('title')+'</span>');});
        };

    });
    function showHideInputValue(argObj, argStrType) {
    if (argStrType == 'focus' && $(argObj).val() == $(argObj).attr('title'))
        $(argObj).val('')
    else if ($(argObj).val() == "")
        $(argObj).val($(argObj).attr('title'))
		}

		function showHidePasswordLabel(argObj, argStrType) {
		    if (argStrType == 'focus')
		        $(argObj).prev().hide()
		    else if ($(argObj).val() == "")
		        $(argObj).prev().show()
		}
};

})(jQuery);

/*
 * jQuery Color Animations
 * Copyright 2007 John Resig
 * Released under the MIT and GPL licenses.
 */

(function(jQuery){

	// We override the animation for all of these color styles
	jQuery.each(['backgroundColor', 'borderBottomColor', 'borderLeftColor', 'borderRightColor', 'borderTopColor', 'color', 'outlineColor'], function(i,attr){
		jQuery.fx.step[attr] = function(fx){
			if ( fx.state == 0 ) {
				fx.start = getColor( fx.elem, attr );
				fx.end = getRGB( fx.end );
			}

			fx.elem.style[attr] = "rgb(" + [
				Math.max(Math.min( parseInt((fx.pos * (fx.end[0] - fx.start[0])) + fx.start[0]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[1] - fx.start[1])) + fx.start[1]), 255), 0),
				Math.max(Math.min( parseInt((fx.pos * (fx.end[2] - fx.start[2])) + fx.start[2]), 255), 0)
			].join(",") + ")";
		}
	});

	// Color Conversion functions from highlightFade
	// By Blair Mitchelmore
	// http://jquery.offput.ca/highlightFade/

	// Parse strings looking for color tuples [255,255,255]
	function getRGB(color) {
		var result;

		// Check if we're already dealing with an array of colors
		if ( color && color.constructor == Array && color.length == 3 )
			return color;

		// Look for rgb(num,num,num)
		if (result = /rgb\(\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*,\s*([0-9]{1,3})\s*\)/.exec(color))
			return [parseInt(result[1]), parseInt(result[2]), parseInt(result[3])];

		// Look for rgb(num%,num%,num%)
		if (result = /rgb\(\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*,\s*([0-9]+(?:\.[0-9]+)?)\%\s*\)/.exec(color))
			return [parseFloat(result[1])*2.55, parseFloat(result[2])*2.55, parseFloat(result[3])*2.55];

		// Look for #a0b1c2
		if (result = /#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})/.exec(color))
			return [parseInt(result[1],16), parseInt(result[2],16), parseInt(result[3],16)];

		// Look for #fff
		if (result = /#([a-fA-F0-9])([a-fA-F0-9])([a-fA-F0-9])/.exec(color))
			return [parseInt(result[1]+result[1],16), parseInt(result[2]+result[2],16), parseInt(result[3]+result[3],16)];

		// Otherwise, we're most likely dealing with a named color
		return colors[jQuery.trim(color).toLowerCase()];
	}

	function getColor(elem, attr) {
		var color;

		do {
			color = jQuery.curCSS(elem, attr);

			// Keep going until we find an element that has color, or we hit the body
			if ( color != '' && color != 'transparent' || jQuery.nodeName(elem, "body") )
				break;

			attr = "backgroundColor";
		} while ( elem = elem.parentNode );

		return getRGB(color);
	};

	// Some named colors to work with
	// From Interface by Stefan Petre
	// http://interface.eyecon.ro/

	var colors = {aqua:[0,255,255],azure:[240,255,255],beige:[245,245,220],black:[0,0,0],blue:[0,0,255],brown:[165,42,42],cyan:[0,255,255],darkblue:[0,0,139],darkcyan:[0,139,139],darkgrey:[169,169,169],darkgreen:[0,100,0],darkkhaki:[189,183,107],darkmagenta:[139,0,139],darkolivegreen:[85,107,47],darkorange:[255,140,0],darkorchid:[153,50,204],darkred:[139,0,0],darksalmon:[233,150,122],darkviolet:[148,0,211],fuchsia:[255,0,255],gold:[255,215,0],green:[0,128,0],indigo:[75,0,130],khaki:[240,230,140],lightblue:[173,216,230],lightcyan:[224,255,255],lightgreen:[144,238,144],lightgrey:[211,211,211],lightpink:[255,182,193],lightyellow:[255,255,224],lime:[0,255,0],magenta:[255,0,255],maroon:[128,0,0],navy:[0,0,128],olive:[128,128,0],orange:[255,165,0],pink:[255,192,203],purple:[128,0,128],violet:[128,0,128],red:[255,0,0],silver:[192,192,192],white:[255,255,255],yellow:[255,255,0]};

})(jQuery);




$(function(){

    var input = $('input#searchInput');
    var divInput = $('div#searchHolder');
    var divInputWidth = divInput.width();
    var outerWidth = divInput.parent().width() - (divInput.outerWidth() - divInputWidth) - 28;
    var submit = $('#searchSubmit');
    var txt = input.val();

    input.bind('focus', function() {
        if(input.val() === txt) {
            input.val('');
        }
        $(this).animate({color: '#fff'}, 300); // text color
        $(this).parent().animate({
            width: outerWidth + 'px',
            backgroundColor: '#fff', // background color
            paddingRight: '43px'
        }, 300, function() {
            if(!(input.val() === '' || input.val() === txt)) {
                if(!($.browser.msie && $.browser.version < 9)) {
                    submit.fadeIn(300);
                } else {
                    submit.css({display: 'block'});
                }
            }
        }).addClass('focus');
    }).bind('blur', function() {
        $(this).animate({color: '#fff'}, 300); // text color
        $(this).parent().animate({
            width: divInputWidth + 'px',
            backgroundColor: '#e8edf1', // background color
            paddingRight: '15px'
        }, 300, function() {
            if(input.val() === '') {input.val(txt)}
        }).removeClass('focus');
        if(!($.browser.msie && $.browser.version < 9)) {
        	submit.fadeOut(100);
        } else {
        	submit.css({display: 'none'});
        }
    }).keyup(function() {
        if(input.val() === '') {
        	if(!($.browser.msie && $.browser.version < 9)) {
        		submit.fadeOut(300);
        	} else {
        		submit.css({display: 'none'});
        	}
        } else {
        	if(!($.browser.msie && $.browser.version < 9)) {
        		submit.fadeIn(300);
        	} else {
        		submit.css({display: 'block'});
        	}
        }
    });
});

$(function () {
    var input = $('input#searchStoreInput');
    var divInput = $('div#searchStoreHolder');
    var divInputWidth = divInput.width();
    var outerWidth = divInput.parent().width() - (divInput.outerWidth() - divInputWidth) - 28;
    var submit = $('#searchStoreSubmit');
    var txt = input.val();

    input.bind('focus', function () {
        if (input.val() === txt) {
            input.val('');
        }
        $(this).animate({ color: '#000' }, 300); // text color
        $(this).parent().animate({
            width: outerWidth + 'px',
            backgroundColor: '#fff', // background color
            paddingRight: '43px'
        }, 300, function () {
            if (!(input.val() === '' || input.val() === txt)) {
                if (!($.browser.msie && $.browser.version < 9)) {
                    submit.fadeIn(100);
                } else {
                    submit.css({ display: 'block' });
                }
            }
        }).addClass('focus');
    }).bind('blur', function () {
        $(this).animate({ color: '#000' }, 300); // text color
        $(this).parent().animate({
            width: divInputWidth + 'px',
            backgroundColor: '#e8edf1', // background color
            paddingRight: '15px'
        }, 300, function () {
            if (input.val() === '') { input.val(txt) }
        }).removeClass('focus');
        if (!($.browser.msie && $.browser.version < 9)) {
            submit.fadeOut(100);
        } else {
            submit.css({ display: 'none' });
        }
    }).keyup(function (event) {
        if (input.val() === '') {
            if (!($.browser.msie && $.browser.version < 9)) {
                submit.fadeOut(300);
            } else {
                submit.css({ display: 'none' });
            }
        } else {
            if (!($.browser.msie && $.browser.version < 9)) {
                submit.fadeIn(300);
            } else {
                submit.css({ display: 'block' });
            }
            if (event.keyCode == 13) { //enter
                $('.findStoreDetail').hide();
                searchStoresSOAP(input.val());
            }
        }
    }).keydown(function (event) {
        if (event.keyCode == 13) { //enter
            return false; //No beep in ie
        }
    });
});

function wizard() {
    $('.productDetailsLightbox').openDOMWindow({
        height: 850,
        width: 1100,
        positionType: 'centered',
        borderSize: 0,
        eventType: 'click',
        windowSource: 'iframe',
        windowPadding: 0,
        windowBGColor: null,
        overlayOpacity: 45,
        loader: 1
    });

    $('.productCompareLightbox').openDOMWindow({
        height: 1250,
        width: 1050,
        positionType: 'centered',
        borderSize: 0,
        eventType: 'click',
        windowSource: 'iframe',
        windowPadding: 0,
        windowBGColor: null,
        overlayOpacity: 45,
        loader: 1
    });

    $('#activity').css({
        display: "none",
        margin: "0px",
        paddingLeft: "0px",
        paddingRight: "0px",
        paddingTop: "0px",
        paddingBottom: "0px",
        position: "absolute",
        width: "auto"
    });
    $('#activity').css("top", ($(window).height() - 15) / 2 + $(window).scrollTop() + "px");
    $('#activity').css("left", ($(window).width() - 15) / 2 + $(window).scrollLeft() + "px");
}

$('.cntSearchCriteriaInfo').live("mouseenter", function () {
    var strId = $(this).attr('id');
    var intId = strId.split('_').pop();
    $('#searchCriteriaDescription_' + intId).show();
});
$('.cntSearchCriteriaInfo').live("mouseleave", function () {
    var strId = $(this).attr('id');
    var intId = strId.split('_').pop();
    $('#searchCriteriaDescription_' + intId).hide();
});


function formatCompareTable() {
    var maxCompareImgHeight = 0;
    $('.tblCompare .rowImages td span img').each(function () {
        if ($(this).attr('height') * 1 > maxCompareImgHeight)
            maxCompareImgHeight = $(this).attr('height') * 1;
    });
    $('.tblCompare .rowImages td span').css('height', maxCompareImgHeight + 'px');

    var intProductAmount = $('.tblCompare tr:nth-child(3) td').size();
    $('.tblCompare').addClass('tblCompare' + intProductAmount + 'products');
}


function getShopSOAPUrl() {
    //return "http://punkt1.local.novicell.dk/shop/webservices/Punkt1Service.asmx";
    return "/shop/webservices/Punkt1Service.asmx";
    //return "http://punkt1dk.novicell.dk.local/webservices/Punkt1Service.asmx";
}

function getBasketSOAP() {
    var url = getShopSOAPUrl();
    var pl = new SOAPClientParameters();
    SOAPClient.invoke(url, "GetBasket", pl, true, getBasketSOAP_callback);
}

function getBasketSOAP_callback(r) {
    updateBasketValue(r[0], r[1])
}

//function addToBasketSOAP(intProductId, intAmount, strAnimSourceElemId) {
function addToBasketSOAP(intProductId, intAmount, objBtnElem) {
    var url = getShopSOAPUrl();
    var pl = new SOAPClientParameters();
    pl.add("productId", intProductId);
    pl.add("itemCount", intAmount);
    pl.add("jobTypeId", -1);
    pl.add("jobServiceIds", []);
    //console.log("Adding punkt1Product_id: " + intProductId + " - amount: " + intAmount);
    SOAPClient.invoke(url, "AddToBasket", pl, true, addToBasketSOAP_callback);
    $(objBtnElem).effect("transfer", { to: $("#basketTop") }, 1500);
}

function addToBasketSOAP_callback(r) {
    //console.log(r);
    updateBasketValue(r[0], r[1]);
}

function updateBasketValue(intProductCount, strPurchaseValue) {
    $('#basketProductCount').html(intProductCount);

    var arrValue = strPurchaseValue.split(":");
    var strValue = arrValue[0];
    strValue = strValue.substr(1); // remove start-bracket before number
    $('#basketCostAmount').html(formatCurrency(strValue));
}

function formatCurrency(amount) {
    var delimiter = "."; // replace comma if desired
    var a = amount.split('.', 2)
    var d = a[1];
    if (null == d || typeof d == "undefined")
        d = "00";
    var i = parseInt(a[0]);
    if (isNaN(i)) { return ''; }
    var minus = '';
    if (i < 0) { minus = '-'; }
    i = Math.abs(i);
    var n = new String(i);
    var a = [];
    while (n.length > 3) {
        var nn = n.substr(n.length - 3);
        a.unshift(nn);
        n = n.substr(0, n.length - 3);
    }
    if (n.length > 0) { a.unshift(n); }
    n = a.join(delimiter);
    if (d.length < 1) { amount = n; }
    else { amount = n + ',' + d; }
    amount = minus + amount;
    return amount;
}



var searchStoreSOAPEmptyQueryResult = null; //Caches result of an empty query (all stores)
var searchStoreLocatorMap = null;
var searchStoreLocatorMapOverLays = [];
var searchStoreLocatorLargeMap = null;
var searchStoreLocatorLargeMapLoaded = false;
var searchStoreDetailMap = null;
var searchStoreDetailMapOverLays = [];
var searchStoreLocatorMapDefaultCenter = new google.maps.LatLng(56.25, 11.39);
var searchStoreLocatorMapDefaultBounds = new google.maps.LatLngBounds(
    new google.maps.LatLng(54.7599, 8.455119999999965),
    new google.maps.LatLng(57.4554, 12.609299999999962)
);

function searchStoresSOAP(q) {
    if (q == '' && searchStoreSOAPEmptyQueryResult != null) {
        searchStoresSOAP_callback(searchStoreSOAPEmptyQueryResult, true);
        return;
    }
    var url = getShopSOAPUrl();
    var pl = new SOAPClientParameters();
    if (q == '') {
        pl.add('searchString', '8000');
        pl.add('km', 1000);
        SOAPClient.invoke(url, 'SearchStores', pl, true, searchStoreSOAPEmptyQuery_callback);
    } else {
        pl.add('searchString', q);
        pl.add('km', 50);
        SOAPClient.invoke(url, 'SearchStores', pl, true, searchStoresSOAP_callback);
    }
}

function searchStoreSOAPEmptyQuery_callback(r) {
    //Sort result by stireZipCode
    //r = r.sort(function (a, b) {
    //    var valA = a.StoreZipCode, valB = b.StoreZipCode;
    //    if (valA < valB)
    //        return -1
    //    if (valA > valB)
    //        return 1
    //    return 0
    //});
    searchStoreSOAPEmptyQueryResult = r;
    searchStoresSOAP_callback(r, true);
}

function searchStoresSOAP_callback(r, fromEmptyQuery) {
    if (fromEmptyQuery !== true && fromEmptyQuery !== false)
        fromEmptyQuery = false;
    var storeList = $('.storeListHolder table tbody');
    storeList.html('');

    //Clear overlays/markers
    for (var i = 0, len = searchStoreLocatorMapOverLays.length; i < len; i++) {
        searchStoreLocatorMapOverLays[i].setMap(null);
    }
    searchStoreLocatorMapOverLays = [];

    var latlngbounds = new google.maps.LatLngBounds();

    if (!fromEmptyQuery || !searchStoreLocatorLargeMapLoaded) {
        if (fromEmptyQuery && !searchStoreLocatorLargeMapLoaded)
            searchStoreLocatorLargeMapLoaded = true;
        for (var i = 0, len = r.length; i < len; i++) {
            var store = r[i];

            if (!fromEmptyQuery) {
                //html
                var tr = $(document.createElement('tr'));
                tr.append($(document.createElement('td')).append($(document.createElement('a')).attr('href', '#findStoreDetail').html(store.StoreAddress)));
                tr.append($(document.createElement('td')).append($(document.createElement('a')).attr('href', '#findStoreDetail').html(store.StoreZipCode)));
                tr.append($(document.createElement('td')).append($(document.createElement('a')).attr('href', '#findStoreDetail').html(store.StoreCity)));
                tr.data('soapData', store);
                tr.click(displayStore);
                storeList.append(tr);
            }

            var latlng = new google.maps.LatLng(store.Lat, store.Lng);
            latlngbounds.extend(latlng);

            //marker
            var marker = new google.maps.Marker({
                position: latlng,
                map: fromEmptyQuery ? searchStoreLocatorLargeMap : searchStoreLocatorMap,
                title: store.StoreName
            });
            marker.set('storeData', store);

            if (!fromEmptyQuery)
                searchStoreLocatorMapOverLays.push(marker);

            google.maps.event.addListener(marker, 'click', function () {
                var data = this.get('storeData');
                displayStoreDataFromMap(data);
            });
        }
    }

    if (searchStoreLocatorMapOverLays.length > 0 && fromEmptyQuery !== true) {
        $('#findStoreListLargeMap').hide();
        $('#findStoreListMap').show();
        //Center and zoom map arround markers
        //searchStoreLocatorMap.fitBounds(latlngbounds);
        google.maps.event.trigger(searchStoreLocatorMap, "resize");
        searchStoreLocatorMap.setCenter(latlngbounds.getCenter());
        searchStoreLocatorMap.setZoom(8);
    } else {
        $('#findStoreListMap').hide();
        $('#findStoreListLargeMap').show();
        google.maps.event.trigger(searchStoreLocatorLargeMap, "resize");
        searchStoreLocatorLargeMap.setCenter(searchStoreLocatorMapDefaultCenter);
        //searchStoreLocatorLargeMap.fitBounds(searchStoreLocatorMapDefaultBounds);
        searchStoreLocatorMap.setZoom(7);
    }
}

function displayStore(obj) {
    displayStoreData($(this).data('soapData'));
}

function displayStoreDataFromMap(data) {
    displayStoreData(data);
    //Jump to anchor
    var currentHref = window.location.href;
    window.location.href = currentHref.substr(0, currentHref.lastIndexOf("#")) + "#findStoreDetail";
}

function displayStoreData(data) {
    searchStoresSOAP(data.StoreZipCode);
    //$('#findStoreListLargeMap').hide();
    //$('#findStoreListMap').show();
    //Update html
    $('#findStoreDetailName1').html(data.StoreName);
    $('#findStoreDetailName2').html(data.StoreName);
    $('#findStoreDetailAddress').html(data.StoreAddress);
    $('#findStoreDetailZipCity').html(data.StoreZipCode + ' ' + data.StoreCity);
    $('#findStoreDetailPhone').html('Tlf.:' + data.StorePhone);
    $('#findStoreDetailFax').html('Fax:' + data.StoreFax);
    $('#findStoreDetailEmail').html('<a href="mailto:' + data.StoreEmail + '">' + data.StoreEmail + '</a>');
    $('.findStoreDetail #contour .storeemail input').val(data.StoreEmail);

    //Clear overlays/markers
    for (var i = 0, len = searchStoreDetailMapOverLays.length; i < len; i++) {
        searchStoreDetailMapOverLays[i].setMap(null);
    }
    searchStoreDetailMapOverLays = [];

    var ot = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday'];
    for (var i = 0; i < ot.length; i++) {
        var e = $('#openingTime' + ot[i]);
        var open = data['StoreOpen' + ot[i]];
        var close = data['StoreClose' + ot[i]];
        var html = '';
        if (/\d\d:\d\d/.test(open)) {
            html = '<p class="openingTime">' + open + '</p><p class="closingTime">' + close + '</p>';
        } else {
            html = '<p class="closed">' + open + '</p>';
        }
        e.empty().html(html);
    }
    $('.openingHours .extraInfo').empty().html(data.StoreOpenCloseNote);

    //Set marker
    var latlng = new google.maps.LatLng(data.Lat, data.Lng);
    var marker = new google.maps.Marker({
        position: latlng,
        map: searchStoreDetailMap,
        title: data.StoreName,
        clickable: false
    });
    searchStoreDetailMapOverLays.push(marker);

    //Make sure details is visible
    $('.findStoreDetail').show();

    //Make sure map is positioned correctly
    google.maps.event.trigger(searchStoreDetailMap, "resize");
    searchStoreDetailMap.setCenter(latlng);
}

$(function () {
    
    if ($('.storeListHolder table tbody').length > 0) {
        $('.findStoreDetail').hide();
        $('.contourNavigation input[type=submit]').val('Send besked');

        $('#searchStoreSubmit').mouseup(function (event) {
            $('.findStoreDetail').hide();
            searchStoresSOAP($('#searchStoreInput').val());
        });

        var latlng = new google.maps.LatLng(56.1778, 10.5372);
        var locatorOptions = {
            zoom: 6,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        searchStoreLocatorMap = new google.maps.Map(document.getElementById('storeLocatorMap'), locatorOptions);
        var locatorLargeOptions = {
            zoom: 7,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        searchStoreLocatorLargeMap = new google.maps.Map(document.getElementById('storeLocatorLargeMap'), locatorLargeOptions);
        var detailOptions = {
            zoom: 14,
            center: latlng,
            mapTypeId: google.maps.MapTypeId.ROADMAP
        };
        searchStoreDetailMap = new google.maps.Map(document.getElementById('storeDetailMap'), detailOptions);

        searchStoresSOAP(''); //Fetch all stores
    }
});

//Search
function submitSearch() {
    var searchTerm = $('#searchInput').val();
    $('#searchForm').attr('action', '/shop/search/' + searchTerm);
    $('#searchInput').remove();
}
