// Define 
var _gaq = [] || _gaq;

(function($, window, document, undefined) {
    if (typeof window.console == "undefined") {
        window.console = {};
        $.each(['log', 'dir', 'time', 'timeEnd', 'clear', 'dirxml', 'info', 'warn', 'debug', 'group', 'trace', 'info', 'table', 'profile', 'profileEnd', 'time', 'timeEnd', 'exception', 'error', 'group', 'groupCollapse', 'groupEnd'], function(i, e) {
            window.console[e] = $.noop;
        });
    }

    // Extend and manipulate jQuery
    jQuery.cookie = function(name, value, options) {
        if (typeof value != 'undefined') { // name and value given, set cookie
            options = options || {};
            if (value === null) {
                value = '';
                options.expires = -1;
            }
            var expires = '';
            if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                var date;
                if (typeof options.expires == 'number') {
                    date = new Date();
                    date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                } else {
                    date = options.expires;
                }
                expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
            }
            // CAUTION: Needed to parenthesize options.path and options.domain
            // in the following expressions, otherwise they evaluate to undefined
            // in the packed version for some reason...
            var path = options.path ? '; path=' + (options.path) : '';
            var domain = options.domain ? '; domain=' + (options.domain) : '';
            var secure = options.secure ? '; secure' : '';
            document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
        } else { // only name given, get cookie
            var cookieValue = null;
            if (document.cookie && document.cookie != '') {
                var cookies = document.cookie.split(';');
                for (var i = 0; i < cookies.length; i++) {
                    var cookie = jQuery.trim(cookies[i]);
                    // Does this cookie string begin with the name we want?
                    if (cookie.substring(0, name.length + 1) == (name + '=')) {
                        cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                        break;
                    }
                }
            }
            return cookieValue;
        }
    };
    jQuery.getScript = function(url, cb, cache) {
        return $.ajax({
            cache: cache,
            url: url,
            success: cb,
            dataType: "script"
        });
    };

    $.fn.scrollTo = function(time) {
            time = time || time == 0 ? time : 2000;
            $("html, body").animate({
                scrollTop: this.offset().top
            }, time);

            return this;
    };

    // Didn't work in Opera ;) checks if browser is opera for now
    if (!jQuery.browser.opera) {
      jQuery.support.crossDomainXHR = "withCredentials" in new XMLHttpRequest() || !!XDomainRequest;
    }

    // Load som scripts
    $.getScript("http://static.tek.no/js/konami.js?cb=1", null, true);

    // General functions
    var Tek = {
        ads: {
            move: function(elementMoveFrom, elementMoveTo) {
                var newPos = document.getElementById(elementMoveTo),
                    oldPos = document.getElementById(elementMoveFrom);
                if (newPos && oldPos) {
                    var x = oldPos.getElementsByTagName("script"),
                        n = x.length,
                        el;
                    while(n--) {
                        el = x[n];
                        el.parentNode.removeChild(el);
                        el = null;
                    }
                    var body = oldPos.parentNode;
                    body.removeChild(oldPos);
                    newPos.innerHTML = "";
                    newPos.appendChild(oldPos);
                }
                return this;
            },
            cleanUp: function() {
                // Hide empty ads
                $("div.ad-moved").each(function() {
                    var ad = $(this);
                    if (ad.height() < 1)
                        ad.closest("div.ads").addClass("hide");
                });
                return this;
            },
            collapseHeader: function() {
                var topAds = $("#topAds");
                if (topAds.find("div.ads").is(":hidden")) {
                    topAds.addClass('hide');
                    $("body").css({
                        backgroundPosition: '0 -154px'
                    }); /*
                    .end().filter(".wallpaper").find("#wrapper").css({
                        backgroundPosition: '0 -154px'
                    }); */
                }
                return this;
            },
            adjustWallpaperSize: function() {
                var wp = $("#wallpaper");
                if (wp.length && 
                    wp.css('backgroundImage') != 'none') {
                    var img = wp.css('backgroundImage')
                                .replace(/\url|\(|\"|\"|\'|\)/g, ''),
                        el = new Image();

                    el.onload = function() {
                        wp.css({
                            height: el.naturalHeight ?
                                el.naturalHeight : el.height
                        });
                        delete el;
                    }
                    el.src = img;
                }
            },
            placeHorseShoeAds: function() {
                var pos = $('#wrapper').offset();
                var left = pos.left + 1018;
                $('#horseShoeRight').css('left', left + 'px');
                var el = $("#horseShoeLeft").find("object, embed, img");
                var left = pos.left - el.width();
                $('#horseShoeLeft').css('left', left + 'px');
            }
        },
        sticky: function(selector, triggerSelector, css, background) {
            var elem = jQuery.type(selector) == "string" ? $(selector) : selector, 
                triggerElem = triggerSelector ? $(triggerSelector) : elem,
                triggerElemHeight = triggerElem.outerHeight(true),
                elemHeight = elem.outerHeight(true),
                win = $(window),
                positionState = 'absolute',
                stopEl = $("#footer"),
                oldCss = {
                    'position': elem.css('position'),
                    'top': elem.css('top'),
                    'left': elem.css('left')
                };
                css = $.extend({
                    'position': 'fixed',
                    'top': elem.offset().top,
                    'left': elem.offset().left
                }, css);

                win.bind('resize', function(e) {
                    if (positionState != 'absolute') {
                        positionState = 'absolute';
                        elem.css({
                            'position': 'absolute',
                            'top': elem.offset().top,
                            'left': oldCss.left
                        });
                    }
                });

            if (background === true)
                css.backgroundAttachment = 'fixed';
            win.bind('scroll', function() {
                var stop = Math.round(stopEl.offset().top);
                if ((win.scrollTop() + elemHeight) > stop - 50) {
                    elem.css({ top: stop - elemHeight, position: 'absolute', left: oldCss.left });
                    positionState = oldCss.position;
                }
                else if (win.scrollTop() > triggerElemHeight) {
                    if (positionState == 'fixed') return;

                    elem.css({
                        top: css.top,
                        position: css.position,
                        left: elem.offset().left
                    });
                    positionState = css.position;
                    if (triggerElem.css('position') === 'fixed')
                        elem.css('top', triggerElemHeight);
                }
                else {
                    positionState = oldCss.position;
        //            oldCss.left = "-" + elem.width() + "px";
                    elem.css(oldCss);
                }
            });
        },
        adjustArticleHeight: function() {
            var actualContent = $("#articleContent").find("div.actualContent"),
                relatedArticles = $("#articleRelatedArticles");
            if (relatedArticles.length) {
                var adjustmentSize = 100,
                    actualContentOffset = actualContent.offset().top,
                    actualContentHeight = actualContent.outerHeight(true) + actualContentOffset,
                    relatedHeight = relatedArticles.outerHeight(true) + relatedArticles.offset().top;

                if (relatedArticles && relatedHeight > actualContentHeight) {
                    actualContent.css('minHeight', (actualContentHeight - actualContentOffset) + (relatedHeight - actualContentHeight));
                }
            }
        },
        togglePlaceholderText: function(e) {
            var that = $(this).addClass("focused");
            if (e.type == "focusin") {
                if (that.val().length > 0) {
                    if (!that.data('initialValue')) {
                        that.data('initialValue', that.val());
                    }
                    if (that.data('initialValue') == that.val()) {
                        that.val("");
                    }
                }
            }
            else if (e.type == "focusout" && that.data('initialValue')) {
                if (that.val().length == 0) {
                    that.val(that.data('initialValue'));
                }
            }
        },
        gotoProduct: function(e) {
            var that = $(this);
            if (that.length) {
                var value = e.target.value,
                    url = that.attr('action');

                window.location = url + '?productId=' + value;
            }
        },
        forceReload: function() {
            return (new Date().valueOf());
        },
        postfixMobile: function(e) {
            $(this).attr('href', function(i, h) {
                if (h.indexOf('noMobile') == -1) {
                    if (h.indexOf('?') != -1) {
                        return h + "&noMobile=1";
                    }
                    else {
                        return h + "?noMobile=1";
                    }
                }
            });
        }
    };
    
    $(window).resize(function() {
        Tek.ads.placeHorseShoeAds();
    });

    // jQuery Extends
    $.extend($.expr[':'], {
        "value-length": function(a, b, c) {
            if (a.value) {
                    var length = c[3].replace(/<|>/, "");
                    if (/</.test(c[3])) {
                        return (a.value.length < length);
                    }
                    else if (/>/.test(c[3])) {
                        return (a.value.length > length);
                    }
                    return (a.value.length == length);
            }
        }
    });
    
    $.fn.extend({
        sticky: function(triggerSelector, css, background) {
            Tek.sticky(this, triggerSelector, css, background);
            return this;
        }
    });
    
    // Stats
    Tek.Stats = {};
    Tek.Stats.google = {};
    Tek.Stats.ish = {};

    // Track ish 
    Tek.Stats.ish.trackView = function(obj) {
        var loc = encodeURIComponent(window.location.toString()),
            url = "http://ish.tek.no/ish_tracker.php?pid=" + obj.pid + "&res=" + obj.req + "&load=" + obj.load + "&uri=" + loc;
        if (document.referrer.length) {
            url += "&ref=" + encodeURIComponent(document.referrer);
        }
        $('<img src="' + url.replace("&", "&amp;", 'g') + '" width="1" height="1" alt="ish" />')
            .appendTo("body")
            .load(function(e) {
                $(this).remove();
            });
    };

    // Various methods for requesting external files
    var fileCache = [];
    Tek.getCSS = function(url) {
        if ($.inArray(url, fileCache) < 0) {
            if (document.createStyleSheet) {
                document.createStyleSheet(url);
            }
            else {
                $("<link rel=\"stylesheet\" type=\"text/css\" />")
                    .attr('href', url)
                    .prependTo("head");
            }
            fileCache.push(url);
        }
    };

    Tek.getScript = function(url, cb) {
        if ($.inArray(url, fileCache) < 0) {
            $.getScript(url, function() {
                fileCache.push(url);
                cb&&cb.apply(this, arguments);
            }, true);
        }
    };

    // Track events
    Tek.Stats.google.trackClick = function(obj) {
        _gaq.push(['_trackEvent', obj.section, obj.action, obj.comment]);
    };


    /**
     * User stuff
     *
     */
    (function() {
        function load(method) {
            return function() {
                var _args = arguments;
                $.getScript('https://min.tek.no/js/mintek.js', function() {
                    Tek[method].apply(null, _args);
                });
            }
        }
        // Populate deferred methods to Tek
        $.each(['login', 'register'], function(i, method) {
            Tek[method] = Tek[method] || load(method); 
        });
    })();

    function adjustTopAdHeight() {
        var topAd = $("#topAds"),
            cssStr = '#topAds div.ad-moved, #topAds div.ad-moved embed, #topAds div.ad-moved iframe, #topAds div.ad-moved img { line-height: 1; }';
        if (topAd.height() > 150) {
            $("<style>" + cssStr + "</style>").appendTo("head");
        }
    }

    // Add onload events
    $(document).on("ready", function() {
        $("#wrapper").on('focus blur', 'input[type=text]:value-length(>0):not(.noPlaceholder), input[type=password]:value-length(>0):not(.noPlaceholder)', Tek.togglePlaceholderText);
        $('.feedRingepriser input').focus(function() {
            $(this).select();
        });
    });
    $(window).on("load", function() {
        Tek.ads.cleanUp()
                .collapseHeader();
        $(".expandableList").find("li").hide().filter(".popular").show();
        $(".expandableList").append("<li><a class='showAll' href='#'>Vis alle</a></li>");
        Tek.ads.adjustWallpaperSize();
        Tek.ads.placeHorseShoeAds();

        $("body").on("click", "div.spoiler .header", function(e) {
            $(this).toggleClass("up")
                   .next("div.spoilerContent").toggle();
        });

        if ($.browser.msie) {
            adjustTopAdHeight();
        }
    }).on("bodyLoaded", function() {
            var body = $(this);
            body.on('change', '#chooseMobile', Tek.gotoProduct);
            if (window.location.search.indexOf("noMobile") != -1) {
                body.on('mousedown', "a:not([href^='http://']), a[href^='http://" + document.domain + "']", Tek.postfixMobile);
            }

            body.on("click", "#subjectMenu a", function() {
                Tek.Stats.google.trackClick({ section: 'Menu', action: $(this).text(), comment: 'Clicked menu item' });
            });

            body.on("click", ".expandableList .showAll", function(ev) {
                ev.preventDefault();
                $(this).hide();
                $(this).parents(".expandableList").find("li").css("display", "block");
            });

    });

    // Expose Tek-object
    window.Tek = Tek;
})(jQuery.noConflict(), this, this.document);

