﻿/**
 * Use the fn_ prefix for classes that are used for hooking up events to elements.
 * Avoid using CSS to style these elements.
 */

function blockNonNumbers(obj, e, allowDecimal, allowNegative, decimalChar, decimalPlaces) {
    var key;
    var isCtrl = false;
    var keychar;
    var reg;

    if (window.event) {
        key = e.keyCode;
        isCtrl = window.event.ctrlKey
    }
    else if (e.which) {
        key = e.which;
        isCtrl = e.ctrlKey;
    }

    if (isNaN(key)) return true;

    keychar = String.fromCharCode(key);

    // check for backspace or delete, or if Ctrl was pressed
    if (key == 8 || isCtrl) {
        return true;
    }

    reg = /\d/;
    var isFirstN = allowNegative ? keychar == '-' && obj.value.indexOf('-') == -1 : false;
    var isFirstD = allowDecimal ? keychar == decimalChar && obj.value.indexOf(decimalChar) == -1 : false;

    if (obj.value.indexOf(decimalChar) != -1 && obj.value.substring(obj.value.indexOf(decimalChar)).length > decimalPlaces)
        return false;

    return isFirstN || isFirstD || reg.test(keychar);
}

var Gehrmans = {}; // Namespace

Gehrmans.Utils = {
    emailRegex: /^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i,
    swedishDateRegex: /^(19|20)(\d{2})-(0[1-9]|1[0-2])-(0[1-9]|[12]\d|3[01])$/,
    integerRegex: /^ *[0-9]+ *$/,
    isInArray: function (a) {
        var o = {};
        for (var i = 0, j = a.length; i < j; i++) {
            o[a[i]] = '';
        }
        return o;
    },
    populateInputWithLabel: function () {
        $('label.fn_move-to-inp').each(function () {
            var txt = $(this).html();
            var inp = $('#' + $(this).attr('for'));
            inp.val(txt);

            inp.focus(function () {
                var $this = $(this);
                if ($this.val().length === 0 || $this.val() === txt) {
                    $this.val('');
                }
            }).blur(function () {
                var $this = $(this);
                if ($this.val().length === 0) {
                    $this.val(txt);
                }
            });
            // Remove the label text from the input
            inp.parents('fieldset:eq(0)').find('.btn-search').click(function (e) {
                if (inp.val() === txt) {
                    inp.val('');
                }
            });
        });
    },
    setPrintLinks: function () {
        $('.fn_print').click(function (e) {
            e.preventDefault();
            window.print();
        });
    },

    Validate: {
        email: function (address) {
            return Gehrmans.Utils.emailRegex.test(address);
        },
        phoneNumber: function (phone) {
            // TODO:
        },
        areaCode: function (num) {
            var result = Gehrmans.Utils.Validate.integer(num);
            if (num.length !== 5) {
                result = false;
            }
            return result;
        },
        integer: function (num) {
            return Gehrmans.Utils.integerRegex.test(num);
        },
        stringLength: function (str, len) {
            if (str.length < len) {
                return false;
            }
            return true;
        },
        swedishDate: function (d) {
            return Gehrmans.Utils.swedishDateRegex.test(d);
        },
        compareString: function (str1, str2) {
            if (str1 !== str2) {
                return false;
            }
            else return true;
        }
    },
    Tabs: {
        init: function () {
            //create tabs on product page/popup
            $(".productTabs").tabs();
            if ($('#tab1').length == 0) {
                $("a[href='#tab1']:parent").hide();
            }

//             GEHR-650 - tab2 should be always visible because it will always contain categorys
//            if ($('#tab2').length == 0) {
//                $("a[href='#tab2']:parent").hide();
//            }
//            else if ($('#tab2 > p').html() == "") {
//                $("a[href='#tab2']:parent").hide();
//            }
//            else if (jQuery.trim($('#tab2 > p').html()) == "") {
//                $("a[href='#tab2']:parent").hide();
//            }

            if ($('#tab3').length == 0) {
                $("a[href='#tab3']:parent").hide();
            }
            else if ($('#tab3 > p').html() == "") {
                $("a[href='#tab3']:parent").hide();
            }
            else if (jQuery.trim($('#tab3 > p').html()) == "") {
                $("a[href='#tab3']:parent").hide();
            }
            if ($('#tab4').length == 0) {
                $("a[href='#tab4']:parent").hide();
            }
            else if (jQuery.trim($('#tab4 > span').html()) == "") {
                $("a[href='#tab4']:parent").hide();
            }
        }
    },
    Lists: {
        cache: [],
        collapse: function () {
            $('.fn_dl-collapsable dt a').click(function (e) {
                e.preventDefault();
                var $this = $(this);
                var $dd = $this.parent('dt').next('dd');
                if ($this.attr('href') in Gehrmans.Utils.isInArray(Gehrmans.Utils.Lists.cache)) {
                    $dd.toggle();
                }
                else {
                    $.ajax({
                        url: $(this).attr('href'),
                        data: 'json=true',
                        dataType: 'json',
                        beforeSend: function () {
                            $dd.show().html('Laddar...');
                        },
                        error: function () {
                            location = $this.attr('href'); // proceed to the url normally
                        },
                        success: function (json) {
                            $dd.html(json.Properties[0].Answer);
                            Gehrmans.Utils.Lists.cache.push($this.attr('href'));
                        }
                    });
                }
            });
        }
    },
    Forms: {
        init: function () {

            $(document).bind('keypress', 'return', function (e) {
                if ($(e.target).parents('.form-validate').length === 1) {
                    if (Gehrmans.Utils.Forms.validate() === true) {
                        $('.fn_validate-form').unbind('click').trigger('click');
                    }
                    else return false;
                }
            });

            $('.fn_validate-form').click(function () {
                return Gehrmans.Utils.Forms.validate();
            });

            // Moves the error message after the inputs.
            // Not possible to place them there per default in Litium.
            $('.fld-rdo .val-message, .fld-chk .val-message').each(function () {
                $(this).closest('div').append($(this));
            });
        },
        validate: function () {
            return Gehrmans.Utils.Forms.findElements();
        },
        findElements: function () {
            var $f = Gehrmans.Utils.Forms;
            var $v = Gehrmans.Utils.Validate;
            // Length of input
            $('.fn_validate-len').each(function () {
                var $elm = $(this).siblings('input');
                if ($v.stringLength($elm.val(), 1) === false) {
                    var mess = $f.Messages.len.replace('{0}', 1);
                    $f.Update.Individual.set($elm, mess);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });
            // Length of textarea
            $('.fn_validate-textarea').each(function () {
                var $elm = $(this).siblings('textarea');
                if ($v.stringLength($elm.val(), 1) === false) {
                    var mess = $f.Messages.len.replace('{0}', 1);
                    $f.Update.Individual.set($elm, mess);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });
            // Group of checkboxes
            $('.fn_validate-chk').each(function () {
                var $elms = $(this).closest('div').next().find('input[type=checkbox]:checked');
                if ($elms.length === 0) {
                    $f.Update.Group.set($(this), $f.Messages.collection);
                }
                else {
                    $f.Update.Group.clear($(this));
                }
            });
            // Integer (whole number)
            $('.fn_validate-int').each(function () {
                var $elm = $(this).siblings('input');
                if ($v.integer($elm.val()) === false) {
                    $f.Update.Individual.set($elm, $f.Messages.integer);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });
            // Group of radio buttons
            $('.fn_validate-rdo').each(function () {
                var $elms = $(this).closest('div').next().find('input[type=radio]:checked');
                if ($elms.length === 0) {
                    $f.Update.Group.set($(this), $f.Messages.collection);
                }
                else {
                    $f.Update.Group.clear($(this));
                }
            });
            // Email validation
            $('.fn_validate-email').each(function () {
                var $elm = $(this).siblings('input');
                if ($v.email($elm.val()) === false) {
                    $f.Update.Individual.set($elm, $f.Messages.email);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });
            // Area code validation
            $('.fn_validate-area-code').each(function () {
                var $elm = $(this).siblings('input');
                if ($v.areaCode($elm.val()) === false) {
                    $f.Update.Individual.set($elm, $f.Messages.areaCode);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });
            // Date validation
            $('.fn_validate-date').each(function () {
                var $elm = $(this).siblings('input');
                if ($v.swedishDate($elm.val()) === false) {
                    $f.Update.Individual.set($elm, $f.Messages.date);
                }
                else {
                    $f.Update.Individual.clear($elm);
                }
            });

            // Move to the first found error
            if ($('.error').length > 0) {
                $.scrollTo($('.error:eq(0)'), {
                    duration: 1000,
                    easing: 'easeOutExpo'
                });

                if ($('.error:eq(0) input:first').length !== 0) {
                    $('.error:eq(0) input:first').focus();
                }
                else { // Assuming we have a textarea.
                    $('.error:eq(0) textarea:first').focus();
                }

                return false;
            }
            else {
                return true;
            }
        },
        Update: {
            Individual: {
                set: function ($elm, message) {
                    $elm.closest('div').addClass('error').find('.val-message').text(message).show();
                },
                clear: function ($elm) {
                    $elm.closest('div').removeClass('error').find('.val-message').hide();
                }
            },
            Group: {
                set: function ($elm, message) {
                    $elm.closest('div').closest('span').addClass('error').find('.val-message').text(message).show();
                },
                clear: function ($elm) {
                    $elm.closest('div').closest('span').removeClass('error').find('.val-message').hide();
                }
            }
        },
        Messages: {
            email: 'Ogiltligt e-postadress',
            areaCode: 'Ange fem siffror',
            integer: 'Ange ett heltal',
            date: 'Ange datum i formatet åååå-mm-dd',
            len: 'Minst {0} tecken',
            collection: 'Välj minst ett alternativ'
        }
    },
    Search: {
        init: function () {
            if ($.browser.msie && parseInt($.browser.version) < 8) {
                // Currently not supported by IE6 and IE7
                // since they have issues with the z-index.
                return;
            }
            else {
                Gehrmans.Utils.Search.Add.optionLayer();
                Gehrmans.Utils.Search.Add.events();
            }
        },
        Add: {
            optionLayer: function () {
                $('fieldset.search select').each(function () {
                    var $div = $('<div></div>').addClass('search-options');
                    var $ul = $('<ul></ul>');
                    $(this).hide().find('option').each(function (index) {
                        var $li = $('<li></li>').attr('rel', index);
                        $li.text($(this).text()).appendTo($ul);
                    });

                    var $sel = $('<span></span>').addClass('selected');
                    $sel.append($ul.find('li:eq(0)').text()).appendTo($div);

                    $ul.appendTo($div.appendTo($(this).closest('.inputs')));
                    $ul.wrap(document.createElement('div'));
                });
            },
            events: function () {
                $('.search-options li').hover(
					function () {
					    $(this).addClass('hover');
					},
					function () {
					    $(this).removeClass('hover');
					}
				)
				.click(function () {
				    $(this).parents('.search-options').find('.selected').text($(this).text());
				    // set attribute selected to the select-element			
				    $(this).closest('div').hide().parents('.search:eq(0)').find('select li[selected=selected]').removeAttr('selected').end().find('select option').eq($(this).attr('rel')).attr('selected', 'selected');
				});
                $('.search-options .selected').click(function () {
                    $(this).next('div').slideToggle('fast');
                });
            }
        }
    },
    Toggling: {
        init: function () {
            Gehrmans.Utils.Toggling.next();
            Gehrmans.Utils.Toggling.prev();
            Gehrmans.Utils.Toggling.text();
        },
        prev: function () {
            $('.fn_toggle-prev').live('click', function (e) {
                e.preventDefault();
                $(this).toggleClass('open').prev().toggle();
            });
        },
        next: function () {
            $('.fn_toggle-next').live('click', function (e) {
                e.preventDefault();
                $(this).toggleClass('open').next().toggle();
            });
        },
        text: function () {
            var toggled = false;
            $('.fn_toggle-text').parent().append($('<span></span>').addClass('cutter').text('...')).end().parent().append($('<div></div>')).append($('<a></a>').click(function (e) {
                e.preventDefault();
                if (toggled === false) {
                    $(this).text('Dölj');
                    toggled = true;
                }
                else {
                    $(this).text('Visa hela beskrivningen');
                    toggled = false;
                }
                $(this).siblings('.fn_toggle-text, .cutter').toggle();
            })
			.text('Visa hela beskrivningen').attr('href', '#'));
        }
    },
    Pagination: {
        scrollToView: function () {
            $.scrollTo($(".pager").prev("ul"), {
                duration: 1000,
                axis: 'y',
                easing: 'easeOutExpo'
            });

            //            $.scrollTo($('div').find('.leftCol')[0], {
            //                duration: 1000,
            //                easing: 'easeOutExpo'
            //            });
        }
    },
    documentActions: function () {
        $(document).click(function (e) {
            if (!$(e.target).hasClass('selected')) {
                $('.search-options > div').hide();
            }
        });
    },
    Filters: {
        init: function () {
            if (filtersApplied === 0) {
                filtersApplied = 1;
                Gehrmans.Utils.Filters.showHidePanel();
                Gehrmans.Utils.Filters.limitItems();
                Gehrmans.Utils.Filters.showHideItems();
            }
        },
        showHidePanel: function () {
            var filtersText = $("#FiltersText").val();
            $("div.filters").prepend("<p><a class='hideFilters' href='#'>" + filtersText + "</a></p>");
            $("a.hideFilters").toggle(
				function () {
				    $("ul.filterList").slideUp();
				    $(this).addClass("showFilters").removeClass("hideFilters");
				},
				function () {
				    $("ul.filterList").slideDown();
				    $(this).addClass("hideFilters").removeClass("showFilters");
				}
			);
        },
        limitItems: function () {
            $("ul.filterList ul").filter(function () {
                return $(this).find("li").length > 4 && !$(this).find("li:gt(3) span").hasClass("selected");
            }).after("<a class='moreFilters' href='#'>" + $("#ctl00_hiddVisaFlerExpand").val() + "</a>").find("li:gt(3)").hide();
            //GEHR-422 - localization of this web string
        },
        showHideItems: function () {
            $("a.moreFilters").toggle(
				function () {
				    $(this).prev("ul").find("li").slideDown();
				    $(this).addClass("lessFilters").removeClass("moreFilters").text($("#ctl00_hiddVisaFlerCollapse").val());
				},
				function () {
				    $(this).prev("ul").find("li:gt(3)").slideUp();
				    $(this).addClass("moreFilters").removeClass("lessFilters").text($("#ctl00_hiddVisaFlerExpand").val());
				}
            //GEHR-422 - localization of this web string
			);
        }
    },
    ProductPopup: {
        init: function () {
            Gehrmans.Utils.Filters.init();
            Gehrmans.Utils.Tabs.init();
            Gehrmans.Utils.ProductPopup.scrollToPopup();
            Gehrmans.Utils.ProductPopup.selectAddress();
        },
        scrollToPopup: function () {
            if ($(".productPopup").length !== 0) {
                $.scrollTo($(".productPopup"), {
                    axis: 'y'
                });

            }
        },
        selectAddress: function () {
            $(".popupHeader address input").click(function () {
                $(this).select();
            });
        }
    },
    init: function () {

        Gehrmans.Utils.populateInputWithLabel();
        Gehrmans.Utils.setPrintLinks();
        //Gehrmans.Utils.TipFriend.init();
        Gehrmans.Utils.Tabs.init();
        //Gehrmans.Utils.Newsletter.init();
        Gehrmans.Utils.Lists.collapse();
        Gehrmans.Utils.Forms.init();
        Gehrmans.Utils.Search.init();
        Gehrmans.Utils.Toggling.init();
        Gehrmans.Utils.documentActions();
        Gehrmans.Utils.Filters.init();
        Gehrmans.Utils.ProductPopup.init();
    }
};

Gehrmans.Carousel = {
	setup: function() {
		
		// Don't continue if we don't have any carousel in the page
		if($('.carousel').length === 0) {
			return;
		}
		
		$('.carousel').carousel({
			width:444,
			height:133,
			rotate:true,
			addNavigation:true,
			vertical:false,
			animSpeed: 500,
			easing: 'easeOutSine'	
		});
		
		$('.carousel-next').click(function(e){
			e.preventDefault();
			if($(this).hasClass('carousel-next-disabled')){
				return;
			}
			var $this = $(this);
			$this.removeClass('carousel-next').addClass('carousel-next-disabled');
			$.carouselNext({
				callback: function() {
					$this.addClass('carousel-next').removeClass('carousel-next-disabled');
				}
			});
		});
		$('.carousel-prev').click(function(e){
			e.preventDefault();
			if($(this).hasClass('carousel-prev-disabled')){
				return;
			}
			$this = $(this);
			$this.removeClass('carousel-prev').addClass('carousel-prev-disabled');
			$.carouselPrev({
				callback: function() {
					$this.addClass('carousel-prev').removeClass('carousel-prev-disabled');
				}
			});
		});		
	}
};

/* ----------------------------
 * Tooltip, used in checkout only
 ---------------------------- */
(function($) {
	$.fn.mtooltip = function(settings) {
		
		// Settings
		settings = $.extend({
			icon: null,
			containerID: null,
			containerClass: null,
			addOffsetTop: 0,
			addOffsetLeft: 0
		}, settings);
				
		var TT = {
			setup: function($this, settings) {
				var $tooltip = $('#' + settings.containerID);
				$this
				.css('cursor', 'pointer')
				.hover(
					function(e) {
						var t = $(this).attr('title');
						$(this).attr('title','');
						var y = Math.round($this.offset().left);
						var x = Math.round($this.offset().top);
						
						$tooltip.css({
							left: (y + settings.addOffsetLeft) + 'px',
							top: (x + settings.addOffsetTop) + 'px'
						}).show().find('> div').html(t);
					},
					function(e) {
						$tooltip.hide();
						$(this).attr('title', $tooltip.text());
					}
				);
			}	
		};
		
		$('body')
			.append(
				$('<div></div>')
				.addClass('tooltip-wrapper')
				.append($('<div></div>')
				.attr('id', settings.containerID)
				.addClass(settings.containerClass)
				.append($('<div></div>').addClass('tooltip-inner'))
			)
		);
		
		return this.each(function() {
			TT.setup($(this), settings);
		});
				
	};
	
})(jQuery);

/* ----------------------------
 * Ready, steady, go
 ---------------------------- */
$(document).ready(function() {
    Gehrmans.Utils.init();
    Gehrmans.AspNet.init();
    Gehrmans.Carousel.setup();

    //Add class to body if javascript is enabled
    $("body").addClass("jsEnabled");

    // Only apply the tooltip if any is defined
    if ($('.fn_tooltip').length > 0) {
        $('.fn_tooltip').mtooltip({
            containerID: 'tooltip-container',
            containerClass: 'tooltip-container',
            addOffsetLeft: 10,
            addOffsetTop: -15,
            icon: '/cui/img/objects/tooltip-icon.png'
        });
    }


    // Temp until it has been moved to code behind.
    $('#sitemap-container ul li:last-child').addClass('last');
    // End.

    // Sets the z-index to 1 so the
    // so the search options doesn't
    // shine through the product basket.
    $('.btn-link').click(function() {
        $('.search-options').css({
            zIndex: "1"
        });
    });



    $('a.ProductPreviewImageLink').click(function() {
        var $c = $(this).next().clone();
        $c.show();
        $('#productimagecontainer').html($c.children()[0]);
        $('#productimagecontainer').append("&nbsp");

        $('.enlargeImageLink')[0].href = $c[0].href;

        return false;
    });

    if ($('#producturl') && $('#producturl').val()) {
        $('#producturl').val(($('#producturl').val()).replace("//", "/").replace("//", "/").replace("http:/", "http://"));
    }
});

/* ----------------------------
 * ASP.NET Ajax related
 ---------------------------- */
Gehrmans.AspNet = {
    postBackElm: null,
    postBackElmTop: 0,
    postBackElmLeft: 0,
    timeout: null,
    BeginRequestHandler: function(sender, args) {

        // Store the postback element source
        Gehrmans.AspNet.postBackElm = $(sender._postBackSettings.sourceElement);
        var $p = Gehrmans.AspNet.postBackElm;

        // Store the coordinate of the postback element		
        if ($p.hasClass('fn_add-to-cart')) {
            Gehrmans.AspNet.postBackElmTop = $p.closest('.product').offset().top;
            Gehrmans.AspNet.postBackElmLeft = $p.closest('.product').position().left;
        }
        // Fades out a product from the shopping cart when deleting.
        // Will not be seen in Internet Explorer or Opera.
        if ($p.hasClass('fn_delete-from-cart')) {
            $p.closest('tr').fadeOut('fast');
        }

        // Removes the confirm layer so we don't end up with duplicate layers in code.
        $('.confirm-layer').remove();

        // Assign this class to all elements that
        // should be hidden when an ajax request is invoked.
        $('.fn_hideOnBegin').hide();
    },
    EndRequestHandler: function(sender, args) {
        // Position the confirm layer after a product has beend added to the product basket.
        // Use the parent product container as a position reference.
        var $confirm = $('.confirm-layer');

        if ($confirm.length > 0) {
            $confirm.css({
                top: Gehrmans.AspNet.postBackElmTop + 'px',
                left: Gehrmans.AspNet.postBackElmLeft + 'px'
            }).appendTo('body'); // Append the layer to the body so no other element with relative position will conflict.
            Gehrmans.AspNet.timeout = setTimeout(function() {
                $confirm.fadeOut();
            }, 3000);
        }

        if (Gehrmans.AspNet.postBackElm && Gehrmans.AspNet.postBackElm.hasClass('fn_scroll-to-view')) {
            Gehrmans.Utils.Pagination.scrollToView();
        }

        //Add css class to cart popup link
        if ($(".cart").is(":visible")) {
            $(".cartLink input").addClass("expanded");
        } else {
            $(".cartLink input").removeClass("expanded");
        }

//        $('#ctl00_Content_TextBoxComment').first().typing({
//            start: function() {                
//            },
//            stop: function() {
//               // __doPostBack('ctl00$Content$TextBoxComment');
//            },
//            delay: 800

//        });
//        var $p = $(sender._postBackSettings.sourceElement);
//        if ($p.length > 0) {
//            var el = $p[0];
//            if (el.name == "ctl00$Content$TextBoxComment") {
//                setTimeout(function() {
//                    //$('#ctl00_Content_TextBoxComment').focus();
//                    $('#ctl00_Content_TextBoxComment').putCursorAtEnd();
//                }, 500);
//            }
//        }

    },
    init: function() {
        $('.fn_update-cart').live('click', function() {
            $(this).hide();
        });
        $('.close-confirm').live('click', function(e) {
            e.preventDefault();
            $('.confirm-layer').fadeOut();
            clearTimeout(Gehrmans.AspNet.timeout);
        });

    }
};

//set variable for checking if filters functionality is already applied
var filtersApplied = 0;

// Register handlers
Sys.WebForms.PageRequestManager.getInstance().add_beginRequest(Gehrmans.AspNet.BeginRequestHandler);
Sys.WebForms.PageRequestManager.getInstance().add_endRequest(Gehrmans.AspNet.EndRequestHandler);
