var HR = window.HR || {};

var hca = {
    init : function () {
        dynGUI.init();
    }
};

HR.FormHelpers = {
    init: function() {
        HR.FormHelpers.moveLabels();
        HR.FormHelpers.Tooltip.setup();
        HR.FormHelpers.ieSixFixes();
        // Other education
        $('.fn_education-change').change(function() {
            var lang = $(this).attr('data-lang');
            if ($(this.options[this.selectedIndex]).attr('data-show-other-education') == 'true') {
                $('.other-education').fadeIn().find('textarea').focus();
            }
            else {
                $('.other-education').fadeOut();
            }
        }).each(function() {
            if ($(this.options[this.selectedIndex]).attr('data-show-other-education') == 'true') {
                $('.other-education').show();
            }
            else {
                $('.other-education').hide();
            }
        });
        // Invoice address
        $('.invoice-address .rdo-list input[type=radio]').click(function() {
            if ($(this).closest('span').hasClass('other-address')) {
                $('.other-invoice-address').fadeIn('fast');
            }
            else {
                $('.other-invoice-address').fadeOut('fast');
            }
        });
        // Other user
        $('.fn_show-other-user input').click(function() {
            if ($(this).index() === 0) {
                $('.other-user').fadeOut('fast');
            }
            else {
                $('.other-user').fadeIn('fast');
            }
        });
        // Default view behaviour
        if ($('.fn_show-other-user input:eq(0)').attr('checked')) {
            $('.other-user').hide();
        }
        else if ($('.fn_show-other-user input:eq(1)').attr('checked')) {
            $('.other-user').show();
        }
        if ($('.invoice-address .rdo-list input[type=radio]:eq(0)').attr('checked')) {
            $('.other-invoice-address').hide();
        }
        else if ($('.invoice-address .rdo-list input[type=radio]:eq(1)').attr('checked')) {
            $('.other-invoice-address').show();
        }
        if ($('.fn_education-change').attr('data-show-other-education') == 'true') {
            $('.other-education').show();
        }
        else {
            $('.other-education').hide();
        }
    },
    Tooltip: {
        setup: function() {
            $('.popupHelper').each(function() {

                var $this = $(this);
                // No title value, return
                if ($this.attr('title') === "") {
                    return;
                }
                var $icon = $('<img />').attr('src', '/harImages/plh.gif').addClass('help-icon')
				.hover(function(e) {
				    $(this).css({ backgroundPosition: '0 -16px' });
				    $('.form-tooltip').show().find('.inner').html($this.attr('title'));
				    HR.FormHelpers.Tooltip.position($(this));
				}, function() {
				    $(this).css({ backgroundPosition: '0 0' });
				    $('.form-tooltip').hide();
				});
                $icon.insertAfter($this);
            });
            var tooltip = $('<div></div>').addClass('form-tooltip')
				.append($('<div></div>').addClass('outer')
				.append($('<div></div>').addClass('inner')))
				.hide().appendTo('body');
        },
        position: function($this) {
            var left = $this.offset().left;
            var top = $this.offset().top;
            $('.form-tooltip').css({
                left: (left + 20) + 'px',
                top: (top + 10) + 'px'
            });
        }
    },
    Validation: {
        validateRegistrationForm: function() {
            var validationErrors = 0;
            // Disable validation on hidden controls
            $('.person-register li:hidden').find('.ucvalidator').each(function() {
                ValidatorEnable(this, false);
            });
            // Enable validation on visible controls
            $('.person-register li:visible').find('.ucvalidator').each(function() {
                ValidatorEnable(this, true);
            });

            // Clear all validation
            for (var i = 0; i < Page_Validators.length; i++) {
                var validator = Page_Validators[i];
                var label = $(validator).closest('li').find(".title label, .title strong");
                var input = $(validator).closest('li').find('.input input, .input select, .input textarea');
                label.removeClass('failedValidation');
                input.removeClass('failedValidation');
            }

            // Validate page
            var valid = Page_ClientValidate();

            // Empty all summaries
            //            $("div.validation-feedback").html("<ol></ol>");
            var itemsHTML = "";

            for (var i = 0; i < Page_Validators.length; i++) {
                var validator = Page_Validators[i];
                var label = null;
                var input = $(validator).closest('li').find('.input input, .input select, .input textarea');

                // Finds the closest label, in cases where multiple labels are in the same hierarchy
                if ($(validator).prevUntil('label').prev('label').length !== 0) {
                    label = $(validator).prevUntil('label').prev();
                }
                else {
                    label = $(validator).closest('li').find(".title label, .title strong");
                }

                if (!validator.isvalid) {
                    label.addClass('failedValidation');
                    input.addClass('failedValidation');

                    var li;

                    if (label.length > 0) {
                        li = "<li>" + validator.errormessage + " : <em>" + label.text() + "</em></li>";
                    } else {
                        li = "<li>" + validator.errormessage + "</li>";
                    }

                    itemsHTML += li;
                    //$("div.validation-feedback ol").append(li);
                    //$("#" + validator.validationGroup).find('ol').append(li);
                    validationErrors++;
                }
            }

            $("div.validation-feedback").html("<ol>" + itemsHTML + "</ol>");

            if (validationErrors > 0) {
                $('.validation-feedback').show();
            }
            else {
                $('.validation-feedback').hide();
            }
            return valid;
        },
        customRequiredInlineHelpValidator: function(validator, value) {
            var isValid = false;
            var val = value.Value.toLowerCase();
            var label = $(validator).prevUntil('label').prev().text().toLowerCase();
            val = $.trim(val);
            label = $.trim(label);
            isValid = val.length > 0 && label !== val;
            value.IsValid = isValid;
        },
        customRequiredDropdownValidator: function(validator, value) {
            var isValid = false;
            var select = $(validator).prev('select');
            isValid = parseInt(select.attr('selectedIndex')) > 0;
            value.IsValid = isValid;
        },
        customRequiredCheckBox: function(validator, value) {
            var isValid = false;
            var cb = $(validator).prev('div').children("input");
            value.IsValid = cb.attr("checked");
        }
    },
    moveLabels: function() {
        if ($('#txtLoggedinUser').val() === 'true') {
            return;
        }
        var helperClass = 'inlineHelper';
        $('label.inlineHelper').each(function() {
            var $this = $(this);
            var $text = $(this).text();
            if ($this.next().val() === '') {
                $this.next('input').attr('title', $text).val($text).addClass(helperClass).focus(function() {
                    var $t = $(this);
                    if ($t.val() === $text) {
                        $t.val('').removeClass(helperClass);
                    }
                }).blur(function() {
                    var $k = $(this);
                    if ($k.val().length === 0) {
                        $k.val($text).addClass(helperClass);
                    }
                });
            }
        });
    },
    ieSixFixes: function() {
        /*
        * IE6 can't handle input[type=text].
        * This is a helper for IE6 sicne we don't wanna cludder
        * up the HTML with classes.
        */
        if ($.browser.msie && parseInt($.browser.version) === 6) {
            $('input[type=text]').each(function() {
                $(this).addClass('iesix-fix').addClass('iesix-type-text');
            });
            $('input[type=password]').each(function() {
                $(this).addClass('iesix-fix').addClass('iesix-type-password');
            });
        }
    }
};

HR.Products = {
	init: function() {
		HR.Products.trimTeaser();
		HR.Products.clickableProductRow();
		HR.Products.viewDescription();
		HR.Products.summarize();
	},
	trimTeaser: function(){
		$('.teaserTxt').truncate({
			max_length: 300,
			more: " L&auml;s mer ",
			less: " D&ouml;lj "
		});		
	},
	clickableProductRow: function(){
		var $productRow = $('ul.productCategoryList').find('li');
		$productRow.click(function(){
			window.location = $(this).find('a').attr('href');
			return false;
		});		
	},
	viewDescription: function() {
		var $desc = $('.product-description');
		$desc.css({position: 'relative'}); // Fix for IE7
		var $height = $desc.find('div:first').height();
		var $a = $('<a></a>').attr('href', '#').text(viewFullDescTxt) //'Visa hela beskrivningen'
		.toggle(function(e) {
			e.preventDefault();
			$(this).addClass('open').text(hideFullDescTxt); //'Dölj hela beskrivningen'
			$desc.animate({
				height: ($height+36) + 'px'
			}, 1000, function() {
				$(this).css({
					overflow: 'visible',
					position: 'static'
				});
			});
		}, function(e) {
			e.preventDefault();
			$(this).removeClass('open').text(viewFullDescTxt); //'Visa hela beskrivningen'
			$desc.animate({
				height: '-=' + ($height) + 'px'
			}, 1000, function() {
				$(this).css({
					overflow: 'hidden',
					position: 'relative'
				});
			});
		});
		var $div = $('<div></div>').addClass('read-more').append($a);
		$div.insertAfter($desc);
	},
	summarize: function() {
		$('.products input.amount').keyup(function() {		    
			var total = 0;
			$('.products input.amount').each(function() {
				
				var $this = $(this);
				var sum, amount;
				// Not a number, force the value to 0
				if(isNaN($this.val())) {
					$this.val('0');
				}
				// No value, use 0
				if($this.val().length === 0) {
					amount = 0;
				}
				// Grab value from input
				else {
					amount = HR.Products.stripWhiteSpace($this.val());	
				}
				
				sum = HR.Products.stripWhiteSpace($this.closest('td').prev('td').find('span').text());				
				sum = HR.Products.validateFloat(sum);
				amount = HR.Products.validateFloat(amount);
				sum =  parseFloat(sum);
				amount = parseFloat(amount);
				
				total += sum * amount;
		    });
			
			total = HR.Products.roundValue(total);
			$('.products-sum .items-total').text(HR.Products.formatResult(total));
		}).blur(function() {
			if($(this).val().length === 0) {
				$(this).val('0');
			}
		});
	},
	// Strip all whitespaces, outside and inside of strings
	stripWhiteSpace: function(val) {
		return val.replace(/\s+/g,'');
	},
	// Replace comma with a dot if the value is a float
	validateFloat: function(val) {
		var re = /,/;
		if (re.test(val)) {
			return val.replace(',', '.');
		}
		else {
			return val;
		}
	},
	// Round to 2 decimals
	roundValue: function(val) {
		return (Math.round(val * 100) / 100);
	},
	formatResult: function(val) {
		var result = val.toString();
		if(val > 999) {			
			var first = result.substring(0,result.length - 3);
			var rest = result.substring(result.length - 3,result.length);
			result = first + " " + rest;
		}
		if(val > 999999) {			
			first = result.substring(0,result.length - 7);
			rest = result.substring(result.length - 7,result.length);
			result = first + " " + rest;
		}
		return result.replace('.', ',');
	}
};

var dynGUI = {
    init : function () {
		if(he.getEsClass("webshop")[0]) {
			dynGUI.sameDLHeight();  
			/*if($.browser.msie && parseInt($.browser.version) === 6) {
				this.ie6();
			};*/
		}
    },
    oddEven : function (node) {
        if(he.get(node).className && he.getClass("oddEven", node)) {
            if(node.nodeName.toLowerCase() === "tbody") {
                var r = 1;
                for (var i = 0; i < node.childNodes.length; i += 1) {
                    if (node.childNodes[i].nodeName.toLowerCase() === "tr") {
                        var pf = parseFloat(r/2); 
                        var pi = parseInt(r/2,10); 

                        if (pf !== pi) {
                            he.addClass("odd", node.childNodes[i]);
							he.addClass("lightbrown", node.childNodes[i]);
                        } else {
                            he.addClass("even", node.childNodes[i]);
                        }
                        
                        r += 1;
                    }
                }
            } else if(node.nodeName.toLowerCase() === "dl") {
                var r = 1;
                for (var i = 0; i < node.childNodes.length; i += 1) {
                    if (node.childNodes[i].nodeName.toLowerCase() === "dt" || node.childNodes[i].nodeName.toLowerCase() === "dd") {
                        var pf = parseFloat(r/2); 
                        var pi = parseInt(r/2,10); 

                        if (pf !== pi) {
                            he.addClass("odd", node.childNodes[i]);
							he.addClass("lightbrown", node.childNodes[i]);
                        } else {
                            he.addClass("even", node.childNodes[i]);
                        }
                        
                        if (node.childNodes[i].nodeName.toLowerCase() === "dd") {
                            r += 1;
                        }
                    }
                }
            }
        }
    },
    sameDLHeight : function () {
        var dls = he.getEsClass("dlsh");
        
        for(var i = 0; i < dls.length; i += 1) {
            var cdt, lcdt, cdd;
            for (var j = 0; i < dls[i].childNodes.length; j += 1) {
                if(dls[i].childNodes[j]) {
                    if(dls[i].childNodes[j].nodeName.toLowerCase() === "dt") {
                        cdt = dls[i].childNodes[j];
                    }
                    if(cdt === lcdt && dls[i].childNodes[j].nodeName.toLowerCase() === "dd") {
                        cdd = dls[i].childNodes[j];
                        if(cdt.offsetHeight !== cdd.offsetHeight) {
                            if (cdt.offsetHeight < cdd.offsetHeight) {
                                cdt.style.height = cdd.offsetHeight + "px";
                                if(cdt.offsetHeight > cdd.offsetHeight) {
                                    cdt.style.height = (cdd.offsetHeight-(cdt.offsetHeight-cdd.offsetHeight)) + "px";
                                }
                            }
                        }
                    }
                    
                    lcdt = cdt;
                } else {
                    break;
                }
            }
        }
    },
    ie6 : function () {
        if(he.get("deliveryAddr")){
            he.wtd(he.get("deliveryAddr"), dynGUI.fillCF);
        }
        dynGUI.setAttrClass();
    },
    fillCF : function (node) {
        if(node.innerHTML && node.innerHTML === "<!-- clearing floats -->") {
            node.innerHTML = "&nbsp;";
        }
    },
    setAttrClass : function () {
        var ht = he.getEsAttr("type");
        for(var i = 0; i < ht.length; i += 1) {
            if(ht[i].nodeName.toLowerCase() === "input") {
                if(ht[i].type === "text") {
                    he.addClass("text",ht[i]);
                }
                if(ht[i].type === "button") {
                    he.addClass("button",ht[i]);
                }
            }
        }
    }
};

var ps = {
	init : function () {
		if (he.get("threePuffs")) {
			ps.puffHeight();
		}
	},
	puffHeight : function () {
		ps.imgH = 0;
		ps.h3h = 0;
		ps.th = 0;
		he.wtd(he.get("threePuffs"), ps.getHeights);
		he.wtd(he.get("threePuffs"), ps.setHeights);
		
		if (he.getEsClass("onlyImage")) {
			ps.aps = he.getEsClass("puff");
			for (ps.i = 0; ps.i < ps.aps.length; ps.i += 1) {
				if (!he.getClass("onlyImage", ps.aps[ps.i])) {
					ps.apH = ps.aps[ps.i].offsetHeight;
					break;
				}	
			}
			
			if (ps.apH) {
				ps.bis = he.getEsClass("bigImg");
				ps.minus = 19;
				if (navigator.userAgent.match(/Firefox/)) {
					// This is a first for me. One thing that is the same in IE 6 & 7, Opera and Safari (for win) but not in Firefox... 
					ps.minus = 18;
				}
				for (ps.i = 0; ps.i < ps.bis.length;ps.i += 1) {
					ps.bis[ps.i].style.height = (ps.apH-ps.minus) + "px";
				}
			}
		}
	},
	getHeights : function (n) {
		if (n.nodeType === 1) {
			if (he.getClass("img", n)) {
				if (n.offsetHeight > ps.imgH) {
					ps.imgH = n.offsetHeight;
				}
			} else if (n.parentNode.tagName.toLowerCase() === "h3") {
				if (n.offsetHeight > ps.h3h) {
					ps.h3h = n.offsetHeight;
				}
			} else if (he.getClass("text", n)) {
				if (n.offsetHeight > ps.th) {
					ps.th = n.offsetHeight;
				}
			} 
		}
	},
	setHeights : function (n) {
		if (n.nodeType === 1) {
			if (he.getClass("img", n)) {
				n.style.height = ps.imgH + "px";
			} else if (n.parentNode.tagName.toLowerCase() === "h3") {
				n.style.height = ps.h3h + "px";
				n.parentNode.style.height = ps.h3h + "px";
			} else if (he.getClass("text", n)) {
				n.style.height = ps.th + "px";
			}
		}
	}
};


/* CAROUSEL */
(function($) {

    $.fn.lcarousel = function(settings) {
        return this.each(function() {

            var options = {};
            var defaults = {
                wrapper: ".list",
                list: "ul",
                pageindex: ".current",
                pagetotal: ".total",
                back: "a.back",
                forward: "a.forward",
                pause: "a.pause",
                play: "a.play",
                speed: 600,
                pagers: ".pager",
                automove: true,
                automoveDelay: 5000,
                selectedPagerClass: "selected",
                playingClass: "playing"
            };

            $.extend(options, defaults, settings);

            var $carousel = $(this);
            var $wrapper = $carousel.find(options.wrapper);
            var $list = $wrapper.find(options.list); // the list
            var $currentpage = $carousel.find(options.pageindex);
            var $totalpages = $carousel.find(options.pagetotal);

            var w = $wrapper.width();
            var itemWidth = $list.find("li").width();

            var h = $list.height();
            var items = $list.children("li").length;
            var itemsPerPage = Math.floor(w / itemWidth);
            var currentPage = 1;
            var totalPages;

            if (items % itemsPerPage == 0)
                totalPages = items / itemsPerPage;
            else
                totalPages = Math.floor(items / itemsPerPage) + 1;

            // set pageinfo
            $currentpage.html(currentPage);
            $totalpages.html(totalPages);

            // set width for list	
            $list.width(itemWidth * items);

            var $back = $carousel.find(options.back);
            var $fwd = $carousel.find(options.forward);
            var $pause = $carousel.find(options.pause);
            var $play = $carousel.find(options.play);

            if (totalPages <= 1) {
                $currentpage.parent().hide();
            }

            // create pager links
            var $pagerLinks = $carousel.find(options.pagers).children();

            $pagerLinks.each(function(index, el) {
                $(this).click(createMoveToIndexFunction(index + 1));
            }).eq(0).addClass(options.selectedPagerClass);

            // the page there moving to
            var movingTo = currentPage;

            // are we're in an animation
            var moving = false;

            // automove
            var automove = options.automove;
            var autotimeout = 0;

            function createMoveToIndexFunction(index) {
                return function(e) {
                    if (currentPage != index) {

                        movingTo = index;
                        if (!moving) {
                            cancelAutomove();
                            move();
                        }
                    }
                    return false;
                }
            }

            function move() {

                if (moving) {
                    // cancel animation
                    $list.stop();
                }

                var totalWidth = (itemWidth * itemsPerPage);
                var left = -((currentPage - 1) * totalWidth);
                var dx = ((movingTo - currentPage) * totalWidth);

                moving = true;

                $pagerLinks.removeClass(options.selectedPagerClass);

                $list.css("left", left + "px");

                $list.animate(
                    {
                        "left": "-=" + dx + "px"
                    },
                    options.speed,
                    moveCompleted);
            }

            function moveCompleted() {

                moving = false;

                // update currentPage
                currentPage = movingTo;

                // Update elements
                $currentpage.html(currentPage);

                // continue move if we're not finished
                if (currentPage != movingTo) {
                    move();
                } else {
                    $pagerLinks.eq(currentPage - 1).addClass(options.selectedPagerClass);
                }

                if (automove) {
                    autotimeout = window.setTimeout(automoveExecute, options.automoveDelay);
                }
            }

            function automoveExecute() {
                // Check if automove is still set
                if (automove) {
                    if (currentPage < totalPages) {
                        movingTo++;
                    } else {
                        currentPage = 0;
                        movingTo = 1;
                    }
                    move();
                    $carousel.addClass(options.playingClass);
                }
            }

            function cancelAutomove() {
                if (automove) {
                    automove = false;
                    if (autotimeout > 0) {
                        window.clearTimeout(autotimeout);
                    }
                    $carousel.removeClass(options.playingClass);
                }
            }

            $play.click(function(e) {


                // Cancel if moving
//                if (automove) {
//                    cancelAutomove();
//                } else {
                    // start if
                    automove = true;
                    startAutoMove();
//                }

                return false;
            });

            $pause.click(function(e) {

                // Cancel if moving
                if (automove) {
                    cancelAutomove();
                } 
                
//                else {
//                    // start if
//                    automove = true;
//                    startAutoMove();
//                }

                return false;
            });


            $back.click(function(e) {

                // disable automatic movement
                cancelAutomove();

                if (movingTo > 1) {
                    movingTo--;
                    move();
                }

                return false;
            });

            $fwd.click(function(e) {

                // disable automatic movement
                cancelAutomove();

                if (totalPages > 1 && movingTo < totalPages) {
                    movingTo++;
                    move();
                }

                return false;
            });

            function startAutoMove() {
                // start automatic movement
                if (automove && totalPages > 1) {
                    autotimeout = window.setTimeout(automoveExecute, options.automoveDelay);
                    $carousel.addClass(options.playingClass);
                }
            }

            // Init automove
            startAutoMove();
        });
    }

})(jQuery);


/* 
DOM READY
*/
$(document).ready(function() {
    HR.Products.init();
    HR.FormHelpers.init();

    // add 
    $("html").addClass("script");

    $("#maincarousel").lcarousel({
        automove: true
    });

    var hash = window.location.hash.substr(1);

    if (hash === "cart")
        $("#topShoppingCartWrapper").addClass("open");

    $("#showShoppingCart").click(function(e) {
        e.preventDefault();
        $("#topShoppingCartWrapper").toggleClass("open");
        return false;
    });
    $("#hideShoppingCart").click(function(e) {
        e.preventDefault();
        $("#topShoppingCartWrapper").toggleClass("open");
        return false;
    });
});
he.addEvent("load", hca.init, window);

