﻿Cufon.replace('.rightMenu a, #mainMenu a, #subMenu a,#accessoriesPage .horscroll-content a .title, #accessoryPage .horscroll-content a .title, #breadCrumb ul li a', { hover: true });
Cufon.replace('h1:not(".nocufon"), h2:not(".nocufon"), h3:not(".nocufon"), h4:not(".nocufon"), h5:not(".nocufon"),  #preview .info p, #preview .info .readMore, .horscroll-content .title, .horizontalScroll .title');


$.fn.horizontalScroll = function (selectedIndex) {
    var selectedIndex = selectedIndex || 1;
    var statuslog = function (string) { $("#status").html(string) };
    var $this = $(this);
    var $that = $this;
    var isHidden = $(this).is(":hidden");
    $this.parent().show();

    var $slider = $this.find(".slider");
    var $viewPort = $this.find(".viewPort");
    var $content = $this.find(".content");
    var sliderWidth = $slider.width();
    var firstItem = $this.find(".content-item:first");

    var itemWidth = firstItem.outerWidth(true);
    var itemCount = $this.find(".content-item").length;
    var padding = $content.outerWidth(true) - $content.innerWidth();
    var contentWidth = (itemWidth * itemCount) + padding;
    $content.css({ "width": contentWidth });

    var sliderContainerWidth = $(".sliderContainer").width();
    var viewPortWidth = $viewPort.width();
    var maxScrollPercent = (contentWidth - viewPortWidth) / 100;

    if (contentWidth == 0 || contentWidth <= viewPortWidth) {
        return $this;
    }
    var $status = $("#status");

    var handlerWidth = sliderWidth / (contentWidth / viewPortWidth);
    sliderWidth = sliderWidth - handlerWidth;
    var sliderPaddingRight = 0;  //handlerWidth;
    var $sliderContainer = $this.find(".sliderContainer");

    var visibleItemCount = viewPortWidth / itemWidth;
    var invisibleItemCount = itemCount - visibleItemCount;

    var initValue = (100 / invisibleItemCount) * (selectedIndex - 1);
    initValue = initValue > 100 ? 100 : initValue;

    $sliderContainer.click(function (e) {
        var offset = $sliderContainer.offset();
        var x = (e.pageX - offset.left) * 100 / sliderContainerWidth;
        value = (x > 50) ? 100 : 0;
        $slider.slider("value", value);
    });

    $slider.css({ 'width': sliderWidth + "px", 'margin-left': (handlerWidth / 2) + "px" });


    var handleSliderChange = function (e, ui) {
        $content.animate({ "left": "-" + maxScrollPercent * ui.value + "px" }, 400);
    }

    var handleSliderSlide = function (e, ui) {
        $status.append("<br/>" + ui.value);
        $content.css({ "left": "-" + maxScrollPercent * ui.value + "px" });
    }

    $slider.slider({
        value: initValue,
        animate: 400,
        change: handleSliderChange,
        slide: handleSliderSlide
    });
    $content.css({ "left": "-" + maxScrollPercent * initValue + "px" });
    $handle = $this.find(".ui-slider-handle");
    $handle.append("<div class='handleLeft'></div><div class='handleBg'></div><div class='handleRight'></div>");
    $handle.css({ 'width': handlerWidth + "px", 'margin-left': "-" + (handlerWidth / 2) + "px" });
    if (isHidden) {
        $this.parent().hide()
    }
};

$.fn.focusedInput = function() {
    $(this).each(function() {
        $(this).focus(function() {
            $(this).addClass('focus');
            if (this.value == this.defaultValue) {
                this.value = '';
            }
        }).blur(function() {
            if (this.value.trim() == '') {
                this.value = this.defaultValue;
                $(this).removeClass('focus');
            }
        });
    });
}

String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g, '');
};


var google_conversion_id = 1058696592;
var google_conversion_language = "sv";
var google_conversion_format = "3";
var google_conversion_color = "ffffff";
var google_conversion_label = "";
var google_conversion_value = 0;
var conversionLabels = {
  'catalog': "W7OlCJzHlgIQkNvp-AM",
  'meeting': "8-Q0CJTIlgIQkNvp-AM"
};


function trackConversion(label) {

    google_conversion_label = label;

    var oldFunction = document.write;
    
    document.write = function (text) {
        jQuery(document.body).append(text);
    };
    
    $.getScript("http://www.googleadservices.com/pagead/conversion.js");
}

function trackFormSubmission(action, target) {
    target = target || "";
    _gaq.push(['_trackEvent', 'Inskickade formulär', action,target]);
}

function onOrderCataloguePage(){
    Cufon.replace('#customerTypePage  h5');
    $("#dialogueCloseBtn").click(function() { $.fancybox.close() });
    $("#errorOkBtn").click(function() { $("#errorMessage").hide(); });
    $('select').uniform({'selectClass' : 'uniSelectBox'});
    
    // order catalogue
    (function () {
        var formIsSubmitted = false;
        $('#orderCataloguePage #submitBtn').click(function () {
            var inputs = $('#orderCataloguePage input[type=text]');
            var name = $(inputs[0]), address = $(inputs[1]), zipCity = $(inputs[2]);
            if (formIsSubmitted === false) {
                if (name.val().trim() == '' || address.val().trim() == '' || zipCity.val().trim() == '' ||
			    name.val() == name[0].defaultValue ||
			    address.val() == address[0].defaultValue ||
			    zipCity.val() == zipCity[0].defaultValue) {
                    $("#errorMessage").show();
                }
                else {
                    formIsSubmitted = true;
                    $.jmsajax({
                        url: webServiceUrl,
                        method: 'OrderCatalogue',
                        data: { name: name.val(), address: address.val(), zipCity: zipCity.val() },
                        success: function (data) {
                            $("#errorMessage").hide();
                            $("#successMessage").show();
                            $("#catSubmit").attr("disabled", "disabled");
                            trackConversion(conversionLabels.catalog);
                            trackFormSubmission("Katalogbeställning","Popup");
                        }
                    });
                }
            }
            return false;
        });
    })();


    // book a meeting
    (function () {
        var formIsSubmitted = false;
        $('#bookAMeetingForm #submitBtn').click(function () {
            var inputs = $('#bookAMeetingForm input[type=text]');
            var hiddenInputs = $('#bookAMeetingForm input[type=hidden]');
            var name = $(inputs[0]), address = $(inputs[1]), zip = $(inputs[2]);
            var city = $(inputs[3]), phone = $(inputs[4]), email = $(inputs[5]);
            var districtId = $('#bookAMeetingForm #chooseDistrict option:selected');
            var message = $('#bookAMeetingForm textarea');
            var formPageId = $(hiddenInputs[1]); 
            var onSuccess = (function(){
                var selectedDistrictName = districtId.text();
                return (function(data){
                        try {
                            // _gaq.push(['_trackEvent', 'Book_meeting', 'Mail', districtId.text()]);
                            $("#errorMessage").hide();
                            $("#successMessage").show();
                            $("#catSubmit").attr("disabled", "disabled");
                            trackConversion(conversionLabels.meeting);
                            trackFormSubmission("Förfrågan om mötesbokning", selectedDistrictName);
                        }
                        catch (err) {}   
                    });
            }());
            if (formIsSubmitted === false) {
                // if any of the cases evaluates o true, the form is invalid (empty field, no district selected, no contact info supplied)
                switch(true){
                    case name.val().trim()      == '': // no name
                    case address.val().trim()   == '': // no address
                    case zip.val().trim()       == '': // no zip
                    case city.val().trim()      == '': // no city
                    case (phone.val().trim()    == '' && email.val().trim() == ''): // no phone or email
                    case districtId.val()       == '-1': // no district selected
                        $("#errorMessage").show();
                        alert("hej");
                        break;
                    default:
                        formIsSubmitted = true;
                        $.jmsajax({
                            url: webServiceUrl,
                            method: 'BookAdviceMeeting',
                            data: { name: name.val(), address: address.val(), zip: zip.val(), city: city.val(), phone: phone.val(), email: email.val(), districtId: districtId.val(), message: message.val(), formPageId: formPageId.val() },
                            success: onSuccess
                        });
                }
            }
            return false;
        });
    })();


    /*
    (function () {
        var formIsSubmitted = false;
        $('#contactForm #submitBtn').click(function () {
            var inputs = $('#contactForm input[type=text]');
            var name = $(inputs[0]), address = $(inputs[1]), zip = $(inputs[2]);
            var city = $(inputs[3]), phone = $(inputs[4]), email = $(inputs[5]);
            var message = $('#contactForm textarea');

            var onSuccess = (function(){
                var selectedDistrictName = districtId.text();
                return 
                    function(data){
                        try {
                            _gaq.push(['_trackEvent', 'Book_meeting', 'Mail', districtId.text()]);
                            $("#errorMessage").hide();
                            $("#successMessage").show();
                            $("#catSubmit").attr("disabled", "disabled");
                            trackConversion(conversionLabels.meeting);
                            trackFormSubmission("meeting request sent", "popup",selectedDistrictName);
                        }
                        catch (err) {}   
                    };
            }());

            if (formIsSubmitted === false) {
                if (
                    name.val().trim() == '' ||
                    address.val().trim() == '' ||
                    zip.val().trim() == '' ||
                    city.val().trim() == '' ||
                    (phone.val().trim() == '' && email.val().trim() == '')
			    ) {
                    $("#errorMessage").show();
                }
                else {
                    formIsSubmitted = true;
                    $.jmsajax({
                        url: webServiceUrl,
                        method: 'RequestContact',
                        data: { name: name.val(), address: address.val(), zip: zip.val(), city: city.val(), phone: phone.val(), email: email.val(), districtId: districtId.val(), message: message.val() },
                        success: function (data) {
                            $("#errorMessage").hide();
                            $("#successMessage").show();
                            $("#catSubmit").attr("disabled", "disabled");
                            trackFormSubmission("contact request sent",
                        }
                    });
                }
            }
            return false;
        });
    })();
    */
}


$(function () {

    $("#addButton").click(
        (function () {
            var count = 0;
            var $container = $("#specifications");
            var itemString = $("#complaintItem").html();
            return function () {
                var oldItemString = itemString;
                do {
                    itemString = itemString.replace("[" + count + "]", "[" + (count + 1) + "]");
                    if (oldItemString === itemString)
                        break;
                    else
                        oldItemString = itemString;
                } while (1);
                $item = $(itemString);
                $item.find('input, textarea').not('input[type=submit], input[type=button]').focusedInput();
                $container.append($item);
                count += 1;
                if (count >= 10) {
                    $(this).parent().hide()
                }
            };
        })()
    );

    //browser version code
    //lte IE 7
    if ($.browser.msie && parseInt($.browser.version, 10) <= 7) {
        //fix for klick event on .puffStart250
        $('.rowNoFloat .puffStart250 a .imgCutWrap').click(function (e) {
            window.location = $(e.target).parent().parent().parent('a').attr('href');
        });
    }
    //browser version code end

    //
    $('#countyDetailsBoxAJAXId .countyAJAX').fancybox({
        'onComplete': function () { Cufon.replace('#retailerDistrict  h3,#retailerDistrict h2'); bindAjaxFancyEvent(); },
        'width': 700,
        'height': 600,
        'transitionIn': ($.browser.msie) ? 'none' : '',
        'transitionOut': ($.browser.msie) ? 'none' : '',
        'speedIn': 400,
        'type': 'ajax',
        'autoDimensions': false,
        'scrolling': 'yes',
        'hideOnContentClick': false
    });
    //


    $("#chooseCounty").change(function () {
        var value = $(this).find(":selected").val();
        if (value != "") {
            document.location = value;
        }
    });

    $(".fancy").each(function () {
        $(this).fancybox({
            'type': 'ajax',
            'onComplete': onOrderCataloguePage
        });

    });

    function bindAjaxFancyEvent() {
        $(".ajaxfancy").fancybox({
            'type': 'ajax',
            'onComplete': onOrderCataloguePage
        });
    }

    $(".ajaxfancy").click(function (event) {
        event.preventDefault();
        $.jmsajax({
            url: $(this).href,
            method: 'POST',
            data: {},
            success: function (data) {
                alert("hurra!");
            }
        });
    });

    $("#tabBox").tabs({
        show: function (event, ui) {
            if ($(ui.panel).attr('id') == 'tabs-1') {

                if ($.browser.msie) {
                    $('#slider').children('#sliderCategory2').hide();
                    $('#sliderCategory1').show();
                }
                else {
                    $('#slider').children('#sliderCategory2').fadeOut();
                    $('#sliderCategory1').fadeIn();
                }
            }
            if ($(ui.panel).attr('id') == 'tabs-2') {

                if ($.browser.msie) {
                    $('#slider').children('#sliderCategory1').hide();
                    $('#sliderCategory2').show();
                }
                else {
                    $('#slider').children('#sliderCategory1').fadeOut();
                    $('#sliderCategory2').fadeIn();
                }
            }
            Cufon.replace('#tabBox .navigation a');
        }
    });

    $('#headerLinks .arrow').click(function () {
        var $a = $(this);

        if ($a.next().is(':visible')) {
            $a.parent().parent().find('.dropDown').hide();
        } else {
            $a.parent().parent().find('.dropDown').hide();
            $a.next().show();
        }

        $a.next().find('.bottomRight').css('width', $a.prev().width() + 38);

        return false;
    });

    $('input, textarea').not('input[type=submit], input[type=button]').focusedInput();

    // Footer form
    $('#footerForm input[type=button]').click(function () {
        var inputs = $('#footerForm input[type=text]');
        var name = $(inputs[0]), address = $(inputs[1]), zipCity = $(inputs[2]);

        if (name.val().trim() == '' || address.val().trim() == '' || zipCity.val().trim() == '' ||
			name.val() == name[0].defaultValue ||
			address.val() == address[0].defaultValue ||
			zipCity.val() == zipCity[0].defaultValue) {
            alert(catError);
            return false;
        }

        $.jmsajax({
            url: webServiceUrl,
            method: 'OrderCatalogue',
            data: { name: name.val(), address: address.val(), zipCity: zipCity.val() },
            success: function (data) {
                alert(catOrdered);
                name.val(name[0].defaultValue);
                address.val(address[0].defaultValue);
                zipCity.val(zipCity[0].defaultValue);
                inputs.removeClass('focus');
                trackConversion(conversionLabels.catalog);
                trackFormSubmission("Katalogbeställning", "Sidfotsformuläret");
            }
        });

        return false;
    });

    $('#horscroll-handle2').hide();

    $('.content-item').hover(
        function (e) {
            var $that = $(this);
            var $bnw = $that.find('.bnw');
            var $color = $that.find('.color');
            var $title = $that.find('.title');
            if ($that.hasClass('selected')) {
            }
            else {
                $title.addClass('hover');
                $bnw.hide();
                $color.show();
            }
            Cufon.replace($title[0]);
        },
        function (e) {
            var $that = $(this);
            var $bnw = $that.find('.bnw');
            var $color = $that.find('.color');
            var $title = $that.find('.title');
            if ($that.hasClass('selected')) {
            }
            else {
                $title.removeClass('hover');
                $bnw.show();
                $color.hide();
            }
            Cufon.replace($title[0]);
        }
    );

    (function () {
        var $selectedObject = $('#categoryPage .horizontalScroll .selected');
        var $selectedPreviewItem = $('#preview .selected');
        $('#categoryPage .horizontalScroll .content-item').click(function () {
            var $this = $(this);
            var $previewItem = $('#preview .item[id="' + $this.attr('rel') + '"]');

            if ($selectedObject !== $this) {
                $selectedObject.removeClass('selected');
                $this.addClass('selected');
                if ($.browser.msie) {
                    $selectedPreviewItem.removeClass('selected');
                    $previewItem.addClass('selected');
                }
                else {
                    $selectedPreviewItem.fadeOut(300, function () {
                        $selectedPreviewItem.removeClass('selected')
                        $previewItem.fadeIn(300).addClass('selected');
                    });
                }
                $selectedPreviewItem = $previewItem;
                $selectedObject = $this;
                Cufon.replace($this.parent().find(".title")[0]);
            }
            return false;
        });

    })();
    // end horizontal scroller

    // "Mockfjärdsmodellen" 
    $('.step').click(function () {
        var obj = $(this);
        if (!obj.hasClass('open'))
            $(this).addClass('open').children('.content').slideDown();
        else
            $(this).removeClass('open').children('.content').slideUp();

    });


    $('select').uniform({
        selectClass: 'uniSelectBox'
    });

    customTabs.init(".tabsWrapper");
    productImageList.init(".topContainerImagelist", ".topContainerImage");

    $("#countySelector").change(function () {
        document.location = $(this).find(":selected").val();
    });

});

var productImageList = {
    selectedListItem: null,
    image: null,
    imageLinkTag: null,
    init: function(listSelector, imageSelector) {
        var that = this;
        this.image = $(imageSelector + " img");
        this.imageLinkTag = this.image.parent();
        this.imageLinkTag.fancybox();
        // $("mainProductImageLink");
        listItems = $(listSelector).find("li").each(function() {
            // "that" is the productImageList-structure
            // "this" is the current list item
            $(this).bind('click', function() {
                $this = $(this);
                var imageSrc = $this.find("img").attr("rel");
                if (that.selectedListItem != null && that.selectedListItem[0] != $this[0]) {
                    that.selectedListItem.find(".background").fadeIn(150, function() {
                        $this.find(".background").fadeOut(150);
                        that.selectedListItem = $this;
                    });
                    that.image.fadeOut(200, function() {
                    that.image.attr('src', imageSrc);
                    that.image.attr('alt', $this.find("img").attr("alt"));
                    that.imageLinkTag.attr('href', imageSrc);
                        that.image.fadeIn(200, function() {
                            that.imageLinkTag.fancybox();
                        });
                    });
                }
            });
        });
        var listItems = $(listSelector + " li ");
        if (typeof (listItems) == typeof ([]) && listItems.length > 0) {
            $(listItems[0]).find(".background").hide();
            this.selectedListItem = $(listItems[0]); 
        }
        else if (typeof (listItems) == typeof ({})) {
            $(listItems).find(".background").hide();
            this.selectedListItem = $(listItems);
        }
    }
}

var customTabs = {
    
    selectedContent: null,
    selectedTab: null,
    init: function(selector) {
    var that = this;
        // add the click handler to the list items
        $(selector + " li ").each(function() {
            // get the href from the inner a tag
            var linkTag = $(this).find('a');
            // prevent the a tag from happen
            linkTag.bind('click', function(event) {
                event.preventDefault();
            })

            // get the content
            var tabContentDiv = $(linkTag.attr('rel'));
            tabContentDiv.hide();
            // bind a click handler to the li
            $(this).bind('click', function() {
                $this = $(this);
                if (that.selectedTab != null && that.selectedTab[0] != $this[0]) {
                    that.selectedTab.removeClass('selected');
                    that.selectedContent.slideUp();
                }
                $this.addClass('selected');
                tabContentDiv.slideDown();

                that.selectedTab = $this;
                that.selectedContent = tabContentDiv;
            });
        }); // end of $(selector + " li ").each

        var listItems = $(selector + " li ");
        if (typeof (listItems) == typeof ([]) && listItems.length > 0) {
            $(listItems[0]).click();
        }
        else if (typeof (listItems) == typeof ({})) {
            $(listItems).click();
        }
    }
}
