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() {
            if ($(this).val() === '0') {
                $('.other-education').fadeIn().find('textarea').focus();
            }
            else {
                $('.other-education').fadeOut();
            }
        }).each(function() {
            if ($(this).val() === '0') {
                $('.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').val() === 0) {
            $('.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.viewDescription();
		HR.Products.summarize();
	},
	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";
			}
		}
	}
};

$(document).ready(function() {
	HR.Products.init();
	HR.FormHelpers.init();
});
he.addEvent("load", hca.init, window);