document.write('<style type="text/css">.jsshow { display: block; } .jshide { display: none; }</style>');

// handle hover gracefully until addthis loads
var addthis_open = function() { },
    addthis_close = function() { },
    addthis_sendto = function() { };

jQuery.easing.def = 'easeOutQuad';

$.extend($.fn.disableTextSelect = function() {
	return this.each(function(){
		if ($.browser.mozilla) {
			$(this).css('MozUserSelect', 'none');
		} else if ($.browser.msie) {
			$(this).bind('selectstart', function() { return false; });
		} else {
			$(this).mousedown(function() { return false; });
		}
	});
});

// home made jQuery plugin to toggle the value of the text input fields on focus / blur
// All it needs is a title attribute on the text input field with the relevant text to be shown / hidden, if there's nothing in the input value field 
$.extend($.fn.toggleInputText = function() {
  var elements = this;
  return (elements.each(function() {
      var el = $(this), title = el.attr('title');
      if (el.val() == "") el.val(title);
      el.focus(function() {
          if (el.val() == title) el.val("");
      }).blur(function() {
          if (el.val() == "") el.val(title);
      });
  }));
});

var MAGASIN = {
    vars: {
        ie: false
    },
    init: function() {
        if ($.browser.msie) {
            MAGASIN.vars.ie = parseInt($.browser.version, 10);
        }
        if (this.vars.ie && this.vars.ie <= 6) {
            $('div.mFashionSelector li').bind('mouseenter mouseleave', function() { $(this).toggleClass('hover'); });
        }

        $.historyInit(this.fashion.articles.pageload);

        this.targets.init();
        this.fashion.init();
        this.openingHours.init();
        this.eventlist.init();
        this.footer.init();
        this.addthis.init();
        this.misc();        
    },
    targets: {
        init: function() {
            $('.target').live('click', function(e) {
                if (e.button === 0) {
                    var $link = $(this).find('a:last');
                    if ($link.length > 0) {
                        var href = $link.attr('href');
                        if (href) {
                            if ($link.attr('target') === '_blank') {
                                window.open(href);
                            } else {
                                document.location = href;
                            }
                            return false;
                        }
                    }
                }
            });
        }
    },
    fashion: {
        init: function() {
            this.articles.init();
            this.medialist.init();
            this.selector.init();
            this.focusBox.init();
            this.linksBox.init();
        },
        medialist: {
            init: function() {
                $('div.mMedialist:not(.binded)').each(function() {
                    var $this = $(this).addClass('binded'),
                        $list = $this.find('ul.medialist'),
                        $links = $this.find('ul.selector li.item a'),
                        active = 0,
                        changeActive = function(no) {
                            var marginLeft = no * -458;
                            active = no;
                            $links.eq(no).parent().addClass('active').siblings('li.active').removeClass('active');
                            $list.animate({
                                'marginLeft': marginLeft
                            }, 400);
                        };

                    $links.mousedown(function() {
                        changeActive($links.index(this));
                    }).click(function() { $(this).blur(); return false; });
                });
            }
        },
        selector: {
            init: function() {
                $('div.mFashionSelector').each(function() {
                    var $selector = $(this),
                        $links_top = $selector.find('div.hd li.pages a'),
                        $links_bottom = $selector.find('div.ft li.pages a'),
                        $prev = $links_top.add($links_bottom).parent().prev().find('a'),
                        $next = $links_top.add($links_bottom).parent().next().find('a'),
                        total = $links_top.length - 1,
                        active = 0,
                        changeActive = function(no) {
                            var marginLeft = no * -140;
                            active = no;
                            $prev.css('visibility', (active === 0) ? 'hidden' : 'visible');
                            $next.css('visibility', (active === total) ? 'hidden' : 'visible');
                            $links_top.eq(no).addClass('active').siblings('a.active').removeClass('active');
                            $links_bottom.eq(no).addClass('active').siblings('a.active').removeClass('active');
                            $links_bottom.parents('div.ft:first').prev().animate({
                                'marginLeft': marginLeft
                            }, 250);
                        };

                    $links_top.mousedown(function() {
                        changeActive($links_top.index(this));
                    }).click(function() { $(this).blur(); return false; });
                    $links_bottom.mousedown(function() {
                        changeActive($links_bottom.index(this));
                    }).click(function() { $(this).blur(); return false; });
                    $prev.add($next).mousedown(function() {
                        var offset = $(this).parent().hasClass('prev') ? -1 : 1;
                        changeActive(active + offset);
                    }).click(function() { $(this).blur(); return false; });
                });
            }
        },
        focusBox: {
            init: function() {
                $('div.mFashionFocus:not(.mFashionFocusExpanded)').each(function(i) {
                    var $box = $(this),
                        $links = $box.find('div.ft a'),
                        max = $links.length,
                        active = 0,
                        timer = null;
                    function interval() {
                        timer = setInterval(function() {
                            active++;
                            if (active === max) { active = 0; }
                            MAGASIN.fashion.focusBox.changeActive($links.filter(':eq(' + active + ')'));
                        }, 3000);
                    }
                    if (i > 0) {
                        setTimeout(function() { interval(); }, i * 1500);
                    } else {
                        interval();
                    }
                    $box.find('div.ft a').hoverIntent({
                        sensitivity: 7,
                        inverval: 150,
                        over: function() {
                            var $link = $(this);
                            active = $links.index($link);
                            clearInterval(timer);
                            MAGASIN.fashion.focusBox.changeActive($link);
                        },
                        out: function() { }
                    }).end().hoverIntent({
                        sensitivity: 7,
                        interval: 150,
                        over: function() { },
                        out: function() { clearInterval(timer); }
                    });
                })
                $('div.mFashionFocus').find('a[href="#"]').live('click', function() {
                    $(this).parent().addClass('active');
                    MAGASIN.fashion.focusBox.getPage(this);
                    return false;
                });
            },
            changeActive: function($elm) {
                var $img = $elm.find('img'),
                    $body = $elm.parents('div.mFashionFocus').find('div.bd'),
                    $span = $body.find('span.img'),
                    $spanImg = $span.find('img'),
                    link = $elm.attr('class'),
                    src = $img.attr('src'),
                    title = $img.attr('alt'),
                    currentSrc = $body.find('img').attr('src');

                if ($spanImg.queue("fx").length > 0) { return; };

                $elm.parent().addClass('active').siblings('li.active').removeClass('active');
                $span.css('backgroundImage', 'url(' + currentSrc + ')').parent().attr('class', link).find('img').stop().hide().attr('src', src).fadeIn(300, 'easeInQuad').end().next().find('a').attr('class', link).html(title);
            },
            getPage: function(elm) {
                var link = $.metadata.get(elm).url,
                    $parent = $(elm).parents('div.mFashionFocus:first').addClass('mFashionFocusLoading');
                $.post(link, { force: true }, function(data) {
                    $.scrollTo($parent, 400, { easing: 'easeInOutQuad' });
                    $parent.removeClass('mFashionFocusLoading').addClass('mFashionFocusExpanded').find('div.bd').replaceWith(data.html).end().find('div.ft').find(' a').unbind('mouseover').end().find('li.active').removeClass('active').hide().siblings().show();
                }, "json");
            }
        },
        linksBox: {
            init: function() {
                $('div.mFashionLinks').each(function(i) {
                    var $box = $(this),
                        $img = $box.find('img'),
                        data = $img.metadata(),
                        images = data.img,
                        active = 0,
                        interval = function() {
                            setInterval(function() {
                                $img.parent().css('backgroundImage', 'url(' + images[active] + ')');
                                active++;
                                if (active === images.length) { active = 0; }
                                $img.hide().attr('src', images[active]).fadeIn(400, 'easeInQuad');
                            }, 3000);
                        }

                    if (images.length > 1) {
                        if (i > 0) {
                            setTimeout(function() { interval(); }, i * 1000);
                        } else {
                            interval();
                        }
                    }
                });
            }
        },
        articles: {
            init: function() {
                $('div.mFashionSelector div.bd li').live('click', function() {
                    var $li = $(this),
              link = $li.find('a').attr('href');
                    if (!window.location.hash.match(link)) {
                        $li.addClass('active loading');
                        $.historyLoad('u=' + link);
                    }
                }).find('a').live('click', function(event) {
                    this.blur();
                    event.preventDefault();
                });

                $('div.main494').prepend('<div id="mainAjax"></div>');
            },
            pageload: function(hash) {
                if (hash && hash.match('u=')) {
                    hash = hash.replace('u=', '');
                    // if($.browser.msie) {
                    //  hash = encodeURIComponent(hash);
                    // }
                    $.post(hash, { force: true }, function(data) {
                        $('div.mFashionSelector li.loading').removeClass('loading').siblings('li.active').removeClass('active');
                        $('#mainAjax').html(data.html).show().next().hide();
                        MAGASIN.fashion.medialist.init();
                        $.scrollTo($('#content'), 400, { easing: 'easeInOutQuad' });
                    }, "json");
                } else {
                    $('#mainAjax').hide().next().show();
                    $.scrollTo($('#content'), 400, { easing: 'easeInOutQuad' });
                }
            }
        }
    },
    openingHours: {
        init: function() {            
            var $div = $('div.openingHours');
            $div.each(function() {
                $div.find('a').mousedown(function() {
                    var $a = $(this),
                        action = $a.attr('class');

                    if (window.openingHours) {
                        currentOpeningHoursIdx = (action == "prev" ? currentOpeningHoursIdx - 1 : currentOpeningHoursIdx + 1);
                        if (currentOpeningHoursIdx < 0) currentOpeningHoursIdx = openingHours.length - 1;
                        if (currentOpeningHoursIdx >= openingHours.length) currentOpeningHoursIdx = 0;
                    }

                    MAGASIN.openingHours.loadData();
                }).click(function() { return false; });
            });

            MAGASIN.openingHours.loadData();
        },
        loadData: function() {
            if (window.openingHours) {
                var openHours = openingHours[currentOpeningHoursIdx];
                if (openHours [8] != "")
                {
                    $('#openWeekNo').text(openHours[8]);
                }
                else
                {
                    $('#openWeekNo').text("Uge " + openHours[0]);
                }
                for (var i = 1; i <= 7; i++) {
                    $('#openData' + i).text(openHours[i]);
                }
            }
        }
    },
    eventlist: {
        init: function() {
            $('ul.list p.readmore a').mousedown(function() {
                $(this).parent().hide().parent().next().slideDown(300);
            }).click(function() { return false; });
        }
    },
    footer: {
        init: function() {
            var height = 0;
            $('div.mFooter > ul > li').each(function() {
                var $li = $(this);
                liHeight = $li.height();
                height = liHeight > height ? liHeight : height;

                if (MAGASIN.vars.ie === 6) {
                    $li.bind('mouseenter mouseleave', function() { $(this).toggleClass('hover'); });
                }
            }).each(function() {
                $(this).height(height);
            });
        }
    },
    addthis: {
        init: function() {
            if ($('li.share').length > 0) {
                // no 'var' as they have to be global
                addthis_brand = "Magasin";
                addthis_header_color = "#ffffff";
                addthis_header_background = "#72007f";
                addthis_language = "da";
                if ($('div.mFashionArticle').length > 0) {
                    addthis_offset_top = -36;
                    addthis_offset_left = 16;
                } else {
                    addthis_offset_top = -23;
                    addthis_offset_left = 19;
                }
                addthis_options = 'email, facebook, favorites, more';
                addthis_exclude = 'print';

                var domscript = document.createElement('script');
                domscript.src = 'http://s7.addthis.com/js/250/addthis_widget.js?pub=magasin';
                document.getElementsByTagName('head')[0].appendChild(domscript);
            }
        }
    },
    misc: function() {
        $('ul.faqlist h3 a').disableTextSelect().mousedown(function() {
            var $li = $(this).parents('li:first');

            if ($li.hasClass('active')) {
                $li.removeClass('active').find('div.jshide').slideUp(300);
            } else {
                $li
                  .addClass('active').find('div.jshide').slideDown(300)
                  .end().siblings('li.active').removeClass('active').find('div.jshide').slideUp(300);
            }
        }).click(function() { $(this).blur(); return false; });

        $('a.print').live('click', function() {
            window.print();
            return false;
        });

        $('table.easyVacancyTableLinks tr').mousedown(function() {
            document.location = $(this).find('a:first').attr('href');
        }).find('a').click(function() { return false; });

        $('#id_matrix input:submit').wrap('<span class="submit"></span>');

        $('#globalSearch :text').toggleInputText();
        $('#globalSearch #searchinput').keypress(function(e) {
            $('#searchErrorMsg').hide();
            if (e.which == 13) {
                $(e.target).parent().parent().find('#btnsimplesearch').click();
                return false;
            }
        });
    },
    easyCruit: {
        submitForm: function() {
            var $div = $('div.mMagasinEasyCruit'),
            username = $div.find('input.username').val(),
            password = $div.find('input.password').val(),
            $form = $('<form method="post" action="https://magasin.easycruit.com/career-center/login" target="_blank"><input type="hidden" name="username" value="' + username + '" /><input type="hidden" name="password" value="' + password + '" /></form>');

            $('body').append($form).find('form:last').submit();

            return false;
        }
    },
    quickSearch: {
        displayError: function() {
            $('#searchErrorMsg').fadeIn(100);
            window.setTimeout("$('#searchErrorMsg').fadeOut(200);", 2000);
        }
    }
}

$(function() {
  MAGASIN.init();
});
