function getLangStr(key, target_lang) {
    if (!key) {return '';}
    if (!target_lang) {target_lang = lang;}
    key = encodeURIComponent(key);
    if (lang_dict[key] && lang_dict[key][target_lang]){
        return decodeURIComponent(lang_dict[key][target_lang]);
    }
    return key;
}

function cropText(text, length, replaceby) {
    replaceby = typeof(replaceby) != 'undefined' ? replaceby : '...';
    if (text.length > length) {
        text = text.substr(0, length);
        text += replaceby;
    }
    return text;
}

function textLimiter(field, countfield, limit) {
    if (field.val().length > limit) {
        field.val(field.val().substring(0, limit));
    } else {
        countfield.html(limit - field.val().length);
    }
}

function init_formfields() {
    $('input, select, textarea, button').mouseenter(function() {
        $(this).addClass('hover');
    });
    $('input, select, textarea, button').mouseleave(function() {
        $(this).removeClass('hover');
    });
    $('input, select, textarea, button').focus(function() {
        $(this).addClass('focus');
    });
    $('input, select, textarea, button').blur(function() {
        $(this).removeClass('focus');
    });
}

function init_formbuttons() {
    $('button').click(function() {
        $(this).val($(this).attr('name'));
    });
}

function init_form_input_activators() {
    $('legend input.activator_0').each(function() {
        var fieldset_fields = $(this).parent().parent().parent().find('.fields');
        if ($(this).is(':checked')) {
            $(fieldset_fields).hide();
        }
        $(this).click(function() {
            if ($(this).is(':checked')) {
                $(fieldset_fields).show();
            } else {
                $(fieldset_fields).hide();
            }
        });
        $(this).change(function() {
            if ($(this).is(':checked')) {
                $(fieldset_fields).hide();
            } else {
                if ($(fieldset_fields).css('display') == 'none') {
                    $(fieldset_fields).show();
                }
            }
        });
    });
    $('legend input.activator_1').each(function() {
        var fieldset_fields = $(this).parent().parent().parent().find('.fields');
        if (!$(this).is(':checked')) {
            $(fieldset_fields).hide();
        }
        $(this).click(function() {
            if ($(this).is(':checked')) {
                $(fieldset_fields).show();
            } else {
                $(fieldset_fields).hide();
            }
        });
        $(this).change(function() {
            if ($(this).is(':checked')) {
                if ($(fieldset_fields).css('display') == 'none') {
                    $(fieldset_fields).show();
                }
            } else {
                $(fieldset_fields).hide();
            }
        });
    });
}

/* quicksearch */
function init_quicksearch() {
    $('.form_quicksearch .input_field').each(function() {
        $(this).attr('standardvalue', getLangStr('search_input', lang));
        $(this).focus(function() {
            if ($(this).val() == $(this).attr('standardvalue')) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if (jQuery.trim($(this).val()) == '') {
                this.value = $(this).attr('standardvalue');
            }
        });
    });
}

function init_fontsize_changer() {
    if ($('ul.fontsizes').length) {
        $('ul.fontsizes .size').click(function() {
            var clicked = this;
            var metadata = $(this).metadata();
            $.cookies.set('font-size', metadata.fontSize);
            $('ul.fontsizes .size').each(function() {
                if (this == clicked) {
                    if (!$(this).hasClass('active')) {
                        $(this).addClass('active');
                    }
                    if ($(this).hasClass('default')) {
                        $('body').removeClass('fontsize_adjusted');
                    } else {
                        if (!$('body').hasClass('fontsize_adjusted')) {
                            $('body').addClass('fontsize_adjusted');
                        }
                    }
                } else {
                    $(this).removeClass('active');
                }
            });
            $('body').css('font-size', metadata.fontSize);
        });
        
        $('ul.fontsizes .decrease').click(function() {
            var prev = $('ul.fontsizes .size.active').prev();
            if (prev.hasClass('size')) {
                prev.click();
            }
        });
        
        $('ul.fontsizes .encrease').click(function() {
            var next = $('ul.fontsizes .size.active').next();
            if (next.hasClass('size')) {
                next.click();
            }
        });
        
        var fontSize = $.cookies.get('font-size');
        if (fontSize) {
            var sizeItem = $.grep($('ul.fontsizes .size'), function(item) {
                return $(item).metadata().fontSize == fontSize;
            });
            if (sizeItem.length > 0) {
                $(sizeItem[0]).click();
            } else {
                $('ul.fontsizes .size.default').click();
            }
        } else {
            $('ul.fontsizes .size.default').click();
        }
        
        $('ul.fontsizes').addClass('loaded');
    }
}

function extend_nyroModalFilters() {
    $.nmFilters({
        text: {
            is: function(nm) {
                var metadata = nm.opener.metadata();
                if (metadata.text && metadata.text.length > 0) {
                    return true;
                } else {
                    return false;
                }
            },
            beforeShowCont: function(nm) {
                var offset = nm.elts.cont.offset();
                var metadata = nm.opener.metadata();
                nm.store.text = $('<div />', {
                    html: decodeURIComponent(metadata.text)
                }).addClass('nyroModalText');
                nm.elts.cont.append(nm.store.text);
            },
            close: function(nm) {
                if (nm.store.text) {
                    nm.store.text.remove();
                    nm.store.text = undefined;
                    delete(nm.store.text);
                }
            }
        }
    });
}

function init_gallery() {
    $('.gallery a, .galleryitem').nyroModal({
        closeButton: '<a href="#" class="nyroModalClose nyroModalCloseButton nmReposition" title="' + getLangStr('Close', lang) + '">' + getLangStr('Close', lang) + '</a>'
    });
}

function init_imagepreview() {
    $('body').delegate('a.imagepreview', 'mouseenter', function() {
        var my_img = $('img', $(this));
        var x_offset = ((my_img.attr('width') - $(this).width())/2)+5;
        var y_offset = ((my_img.attr('height') - $(this).height())/2)+5;
        $(this).qtip({
            overwrite: true,
            content: {
                text: function() {
                    returnvalue = $(this).clone();
                    returnvalue.removeAttr('rel');
                    returnvalue.removeClass('imagepreview');
                    returnvalue.removeClass('vertical-middle');
                    returnvalue.removeAttr('style')
                    returnvalue.data('origin', $(this));
                    return returnvalue;
                }
            },
            hide: {
                fixed: true
            },
            show: {
                ready: true
            },
            position: {
                my: 'top left',
                at: 'left top',
                adjust: {
                    x: -x_offset,
                    y: -y_offset
                }
            },
            style: {
                classes: 'ui-tooltip-imagepreview',
                tip: false
            }
        });
    });
}

function init_tooltip_imagepreview() {
    $('body').delegate('.ui-tooltip-imagepreview a', 'click', function(event) {
        event.preventDefault();
        $(this).data('origin').click();
        $('.qtip').qtip('hide');
    });
}

function init_overview_imagepreview() {
    $('body').delegate('.overview a.imagepreview, .shop_overview a.imagepreview', 'click', function(event) {
        window.location = $(this).attr('href');
    });
}

function init_playvideo() {
    try {
        $('.playvideo').each(function() {
            flowplayer($(this).attr('id'), '/++resource++zmshooks/swf/flowplayer.swf');
        });
    } catch (e) {}
}

function init_locationmap() {
    if ($('.locationmap, .locationsmap').length > 0) {
        $.getScript('http://maps.google.com/maps/api/js?sensor=false&language=' + language_codes[lang]['iso-639-1'] + '&async=2&callback=jQuery.noop');
    }
    
    $('.locationmap, .locationsmap').not($('.tabcontainer_item .locationmap')).each(function() {
        eval($(this).metadata().init_function)();
    });
}

function init_tabcontainer() {
   $('.tabcontainer').each(function() {
       
        var container = $(this);
        $('.tabcontainer_navigation a', container).each(function() {
            $(this).click(function(event) {
                event.preventDefault();
                var clicked = this;
                $('.tabcontainer_navigation a', container).each(function(index) {
                    var target = $($(this).attr('href'))
                    if (this == clicked) {
                        $.cookies.set(container.attr('id'), index.toString());
                        if (!$(this).hasClass('active')) {
                            $(this).addClass('active');
                        }
                        if (!target.hasClass('active')) {
                            target.addClass('active');
                        }
                        $('.locationmap', target).each(function() {
                            eval($(this).metadata().init_function)();
                        });
                    } else {
                        $(this).removeClass('active');
                        target.removeClass('active');
                    }
                });
            });
        });
        
        if (document.location.toString().match('#')) {
            var myAnchor = '#' + document.location.toString().split('#')[1];
            if (myAnchor.length > 1 && $(myAnchor).length > 0 && $('.tabcontainer_navigation a[href="' + myAnchor + '"]', container).length > 0) {
                $('.tabcontainer_navigation a[href="' + myAnchor + '"]', container).click();
            }
        }
        if ($.cookies.get(container.attr('id'))) {
            $($('.tabcontainer_navigation li a', container)[$.cookies.get(container.attr('id'))]).click();
        }
        if (!$('.tabcontainer_navigation a.active', container).length > 0) {
            $('.tabcontainer_navigation li:first a', container).click();
        }
       
        $(this).addClass('loaded');
   });
}

function init_header_promotion() {
    if (!($.browser.msie && $.browser.version <= 6)) {
        $('#header_promotion > div').wrapAll('<div class="wrapper" style="width:100%; height:100%;" />');
        $('#header_promotion > .wrapper').cycle({fx: 'cover', timeout: 8000});
    }    
}

function init_header_images() {
    if (!($.browser.msie && $.browser.version <= 6)) {
        $('#header_images > div').wrapAll('<div class="wrapper" style="width:100%; height:100%;" />');
        $('#header_images > .wrapper').cycle({fx: 'cover', timeout: 8000});
    }
}

function init_slideshow() {
    if (!($.browser.msie && $.browser.version <= 6)) {
        $('.slideshow').each(function() {
            var slideshow = $(this);
            slideshow.addClass('loaded');
            
            var navigation = $('<div class="navigation" />').prependTo(slideshow);
            
            var navigation_control = $('<ul class="control" />').appendTo(navigation);
            $('<li><a href="#" class="btn_play active" title="' + getLangStr('Play') + '"><span>' + getLangStr('Play') + '</span></a></li>').appendTo(navigation_control);
            $('<li><a href="#" class="btn_stop" title="' + getLangStr('Stop') + '"><span>' + getLangStr('Stop') + '</span></a></li>').appendTo(navigation_control);
            
            $('.btn_play', slideshow).click(function() {
                if (!$(this).hasClass('active')) {
                    $(this).addClass('active');
                    $('.btn_stop', slideshow).removeClass('active');
                    $('> .items', slideshow).cycle('resume');
                }
            });
            $('.btn_stop', slideshow).click(function() {
                if (!$(this).hasClass('active')) {
                    $(this).addClass('active');
                    $('.btn_play', slideshow).removeClass('active');
                    $('> .items', slideshow).cycle('pause');
                }
            });
            
            var navigation_items = $('<div class="nav_items" />').appendTo(navigation);
            var navigation_items_list = $('<ul />').appendTo(navigation_items);
            $('> .items > .slideshow_item', slideshow).each(function(index) {
                var metadata = $.parseJSON(decodeURIComponent($(this).metadata().data));
                metadata.index = index;
                $(this).data('metadata', metadata);
                var list_item = $('<li />');
                var link = $('<a href="#' + $(this).attr('id') + '" />').appendTo(list_item);
                if (metadata.titleimage) {
                    var span_titleimage = $('<span class="titleimage vertical-middle" style="background-image:url(' + metadata.titleimage.preview_url + ');"></span>').appendTo(link);
                } else {
                    var span_index = $('<span class="index">' + (index + 1) + '</span>').appendTo(link);
                }
                if (metadata.title) {
                    $('<span class="title">' + metadata.title + '</span>').appendTo(link);
                }
                list_item.appendTo(navigation_items_list);
                
                if ($('.title', link).length > 0) {
                    link.qtip({
                        overwrite: true,
                        content: {
                            text: function() {
                                returnvalue = $(this).clone();
                                returnvalue.data('origin', $(this));
                                returnvalue.click(function(event) {
                                    event.preventDefault();
                                    $(this).data('origin').click();
                                    $('.qtip').hide();
                                });
                                return returnvalue;
                            }
                        },
                        hide: {
                            fixed: true
                        },
                        position: {
                            my: 'top left',
                            at: 'left top'
                        },
                        style: {
                            classes: 'ui-tooltip-slideshow-nav_item',
                            tip: false
                        }
                    });
                }
                
                link.click(function(event) {
                    event.preventDefault();
                    $('> .items', slideshow).cycle(index);
                    $('.btn_stop', slideshow).click();
                })
            });
            
            var last_nav_item = $('.navigation .nav_items li', slideshow).last();
            if ((last_nav_item.position().top + last_nav_item.height()) > $('.navigation .nav_items', slideshow).height()) {
                var nav_max_top_margin = -(last_nav_item.position().top + last_nav_item.height() - $('.navigation .nav_items', slideshow).height());
            } else {
                var nav_max_top_margin = 0;
            }
            
            $('> .items', slideshow).cycle({
                fx: 'scrollHorz',
                timeout: 8000,
                before: function() {
                    var data = $(this).data('metadata');
                    $('.navigation .nav_items li', slideshow).removeClass('active');
                    var nav_item = $($('.navigation .nav_items li', slideshow)[data.index]);
                    nav_item.addClass('active');
                    new_top_margin = -(nav_item.position().top - ($('.navigation .nav_items', slideshow).height() - nav_item.height())/2);
                    if (new_top_margin <= nav_max_top_margin) {
                        new_top_margin = nav_max_top_margin;
                    } else if (new_top_margin >= 0) {
                        new_top_margin = 0;
                    }
                    $('.navigation .nav_items ul', slideshow).animate({marginTop: new_top_margin});
                }
            });
        });
    }
}

function init_tooltip_links() {
    $('body').delegate('a.tooltip-link', 'click', function(event) {
        event.preventDefault();
    });
    $('body').delegate('a.tooltip-link', 'mouseenter', function() {
        $(this).qtip({
            overwrite: true,
            content: {
                text: function() {
                    var returnvalue = $($(this).attr('href')).clone();
                    returnvalue.removeClass('tooltip-target');
                    return returnvalue;
                }
            },
            hide: {
                fixed: true
            },
            show: {
                ready: true
            },
            position: {
                target: 'mouse',
                adjust: {
                    mouse: false,
                    x: 10
                },
                viewport: $(window)
            },
            style: {
                classes: 'ui-tooltip-target'
            }
        });
    });
}

$(function() {
    init_formfields();
    init_formbuttons();
    init_form_input_activators();
    init_quicksearch();
    init_fontsize_changer();
    init_tabcontainer();
    extend_nyroModalFilters();
    init_header_promotion();
    init_header_images();
    init_gallery();
    init_imagepreview();
    init_tooltip_imagepreview();
    init_overview_imagepreview();
    init_playvideo();
    init_slideshow();
    init_locationmap();
    init_tooltip_links();
});
