try {
    if (!ls) ls = {};
} catch(e) {
    ls = {};
    ls.utils = {
        compile : function(string, dict) {
            var string = unescape(string);
            for (var p in dict) {
                var re = new RegExp('\\${'+p+'}', 'g');
                string = string.replace(re, dict[p]);
            }
            return string;
        }
    };
}
String.prototype.compile = function(dict) {
    return ls.utils.compile(this, dict);
}

$(document).ready(function(){
    $(document).ajaxify();
});

jQuery.fn.ajaxify = function() {
    $('.jsLightBoxed', this).lightBoxed();
    $('.jsFormErrors', this).highlightErrors();
    $('.jsSlideNavi', this).slideNavi();
    $('.jsProductImage', this).productImage();
    $('form.jsTitleLabeled', this).titleLabelForm();
    $('form.jsRefreshableForm', this).refreshableForm();
    $('.jsTrack', this).trackEvent();
    $('.jsTrackOnLoad', this).trackEventOnLoad();

    //fix all internal links
    $('a').each(function() {
        var link = $(this);
        if (   link.attr('href')
            && link.attr('href').indexOf('${intern}') === 0) {
            link.attr('href', link.attr('href').replace('${intern}', GLOBALS.portalUrl));
        }
    });
    
    //fix newslist heights
    $('ul.newsList li.entry').each(function() {
        var entry = $(this);
        var ih = $('img', entry).height();
        var dh = $('div', entry).height();
        entry.height(Math.max(ih, dh));
    });
}

jQuery.fn.lightBoxed = function() {
    this.each(function() {
        var selector = "a[rel="+$(this).attr('ajax:marker')+"]";
        
        var paths = {
            imageLoading:           'images/lightbox-ico-loading.gif',  
            imageBtnPrev:           'images/lightbox-btn-prev.gif',     
            imageBtnNext:           'images/lightbox-btn-next.gif',     
            imageBtnClose:          'images/lightbox-btn-close.gif',    
            imageBlank:             'images/lightbox-blank.gif'
        };

        for (var p in paths) {
            paths[p] = GLOBALS.skinUrl + '/fileadmin/lightbox/' + paths[p];
        }
        
        $(selector).lightBox(paths);
    });
}

jQuery.fn.titleLabelForm = function() {
    var focusField = function() {
        var field = $(this);
        if (field.val() == field.attr('title')) field.val('');
    };

    var blurField = function() {
        var field = $(this);
        if (!field.val()) field.val(field.attr('title'));
    };

    $(this).each(function() {
        var form = $(this);
        var fields = $(':input', form);
        
        fields.each(function() {
            var field = $(this);
            if (field.attr('title')) {
                var title = field.attr('title');
                blurField.call(this);
                field.bind('focus', focusField);
                field.bind('blur', blurField);
            }
        });
        form.bind('submit', function() {
            fields.each(focusField);
        });
    });
}

jQuery.fn.highlightErrors = function() {
    $(this).each(function() {
        var node = $(this);
        var form = $(node.attr('ajax:target'));
        $('li', node).each(function() {
            var error = $(this);
            var field = $('*[name='+error.attr('ajax:fieldname')+']', form);
            field.addClass('error');
            field.bind('focus', function() {
                $(this).removeClass('error');
            });
        });
    });
}

jQuery.fn.refreshableForm = function() {
    
    var hideLoader = function() {
        var self=this;
        setTimeout(function() {
            self.slideDown("slow");
            self.next().slideUp("slow");
        }, 1000);
    };
    
    $(this).each(function() {
        var node = $(this);
        if (!node.parent().is('.jsRC')) node.wrap('<div class="jsRC"></div>');
        var target = node.parent();
        node.ajaxForm({
            target: target,
            beforeSubmit : function() {
                target.data('animating', true);
                target.next().slideDown("slow");
                target.data('submitting', true);
                target.slideUp("slow", function() {
                    target.data('animating', false);
                    if (!target.data('submitting')) hideLoader.call(target);
                });
            },
            success: function() {
                target.ajaxify();
                target.data('submitting', false);
                if (!target.data('animating')) hideLoader.call(target);
            }
        });
    });
}

jQuery.fn.trackEvent = function() {
    //track events
    this.each(function() {
        var trackevent = $(this).attr('js:trackevent') || 'click';
        $(this).bind(trackevent, function() {
            dh.trackEvent($(this).attr('js:track'));
        });
    });
}

jQuery.fn.trackEventOnLoad = function() {
    //track events
    this.each(function() {
        dh.trackEvent($(this).attr('js:track'));
    });
}

jQuery.fn.slideNavi = function() {
    this.each(function() {
        var navi = new dh.SlideNavigation();
        navi.init($(this));
    });
}

jQuery.fn.globalToLocal = function(pos) {
    var os = this.offset();
    return {
        x : Math.round(pos.x - os.left),
        y : Math.round(pos.y - os.top)
    };
}

jQuery.fn.productImage = function() {}

dh = {
    VERSION : "0.0.1",
    AUTHOR  : "canislupus.at"
};

dh.trackEvent = function(rpar) {
    var params = rpar.split(','); //category,option,label,value
    params.unshift('_trackEvent');
    // console.log(params);
    _gaq.push(params);
}

dh.SlideNavigation = function() {}
dh.SlideNavigation.EASE = 26;
dh.SlideNavigation.prototype.init = function(context) {
    this.context=context;
    this.strip = $('ul', context);
    this.items = $('li', this.strip);
    this.itemWidth = this.items.width() + 1;
    this.strip.width(this.items.length * this.itemWidth);
    
    var self = this;
    this.context.hover(function() {
        self.activate();
    }, function() {
        self.deactivate();
    });
    
    //clickevent for all lis
    $('li', this.context).bind('click', function(event) {
        event.preventDefault();
        top.location.href = $('a', $(this)).attr('href');
    });
    
    this.preAlign();
    
    //preload hover images
    this.items.each(function() {
        var iurl = $(this).css('backgroundImage').replace('.png', '_hover.png').match(/^url\((.+)\)/)[1];
        $('body').append('<img src=${iurl} style="display:none" width="0" height="0" />'.compile({iurl:iurl}));
    });
}    
dh.SlideNavigation.prototype.activate = function() {
    var self=this;
    this.context.unbind('mousemove').bind('mousemove', function(event) {
        var lc = $(this).globalToLocal({
            x : event.pageX,
            y : event.pageY
        });
        self.timeFactor--; 
        if (self.timeFactor <= 0) self.timeFactor = 1;
        self.slideTo(lc);
    });
    clearInterval(this.slideInt);
    this.strip.stop();
    this.mousePos = 0;
    this.timeFactor = 30;
    this.slideInt = setInterval(function() {
        self.interpolateMouse();
        self.interpolateSlide();
    }, 35);
}

dh.SlideNavigation.prototype.slideTo = function(pos) {
    var to = this.translate(pos);
    this.targetMousePos = to;
}

dh.SlideNavigation.prototype.interpolateMouse = function() {
    this.mousePos = Math.round(this.targetMousePos + (this.mousePos - this.targetMousePos) / dh.SlideNavigation.EASE);
}

dh.SlideNavigation.prototype.interpolateSlide = function() {
    var current = parseInt(this.strip.css('marginLeft'), 10);
    this.targetPos = Math.round(current + ((this.mousePos - current) / (dh.SlideNavigation.EASE * this.timeFactor)));
    this.strip.css('marginLeft', this.targetPos);
    return current == this.targetPos;
}

dh.SlideNavigation.prototype.translate = function(pos) {
    var cw = this.context.width();
    var sw = this.strip.width();
    var diff = cw - sw;
    return Math.round((pos.x / cw) * diff);
}

dh.SlideNavigation.prototype.deactivate = function() {
    this.context.unbind('mousemove');
    clearInterval(this.slideInt);
    this.postAlign();
}

dh.SlideNavigation.prototype.postAlign = function() {
    var current = parseInt(this.strip.css('marginLeft'), 10);
    var align = Math.round(current / this.itemWidth) * this.itemWidth;
    this.strip.stop().animate({'marginLeft' : align}, 1000);
}

dh.SlideNavigation.prototype.preAlign = function() {
    var url = top.location.href;
    var active = $('a[href='+url+']', this.context).closest('li');
    if (active.length) {
        var global = active.offset();
        var local = this.strip.globalToLocal({
            x : global.left,
            y : global.top
        });
        
        console.log(local.x, this.context.width());
        if (local.x >= this.context.width()) {
            this.strip.css({'marginLeft': Math.max(-local.x, this.context.width() - this.strip.width())});
        }
    }

}


