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

function cropText(text, length, replaceby) {
    replaceby = typeof(replaceby) != 'undefined' ? replaceby : '...';
    if (text.length > length + replaceby.length) {
        text = text.slice(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() {
    $('body').delegate('input, select, textarea, button', 'mouseenter', function() {
        $(this).addClass('hover');
    });
    $('body').delegate('input, select, textarea, button', 'mouseleave', function() {
        $(this).removeClass('hover');
    });
    $('body').delegate('input, select, textarea, button', 'focus', function() {
        $(this).addClass('focus');
    });
    $('body').delegate('input, select, textarea, button', 'blur', function() {
        $(this).removeClass('focus');
    });
    
    $('body').delegate('div.formfield-input-checkbox input', 'change', function() {
        var container = $(this).parentsUntil('div.formfield').parent();
        if ($(this).is(':checked')) {
            container.addClass('active');
        } else {
            container.removeClass('active');
        }
    });
    $('div.formfield-input-checkbox').each(function() {
        if ($('input', $(this)).is(':checked')) {
            $(this).addClass('active');
        } else {
            $(this).removeClass('active');
        }
    });
    
    $('body').delegate('div.formfield-input-radio input', 'change', function() {
        $this = $(this);
        var $listcontainer = $this.parentsUntil('fieldset.formradiolist').parent();
        $('div.formfield-input-radio', $listcontainer).removeClass('active');
        if ($this.is(':checked')) {
            $this.parentsUntil('div.formfield').parent().addClass('active');
        }
    });
    $('fieldset.formradiolist').each(function() {
        $listcontainer = $(this);
        $formfields = $('div.formfield-input-radio', $listcontainer);
        $formfields.removeClass('active');
        $formfields.each(function() {
            var $formfield = $(this);
            var $input = $('input', $formfield);
            if ($input.is(':checked')) {
                $formfield.addClass('active');
            }
        });
    });
}

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

/* body_search */
function init_body_search() {
    $('#body_search').delegate('input.raw', 'focus', function() {
        if ($(this).val() == $(this).data('default')) {
            this.value = '';
        }
    });
    $('#body_search').delegate('input.raw', 'blur', function() {
        if ($.trim($(this).val()) == '') {
            this.value = $(this).data('default');
        }
    });
}

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:not(.overview a.imagepreview)', 'mouseenter', function() {
        var my_img = $('img', $(this));
        var x_offset = ((my_img.width() - $(this).width())/2)+5;
        var y_offset = ((my_img.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'),
                flowplayer_url
            );
        });
    } 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)) {
        var $header_promotion = $('#header_promotion');
        if ($header_promotion.length > 0) {
            $('> div', $header_promotion).wrapAll('<div class="wrapper" style="width:100%; height:100%;" />');
            $('> .wrapper', $header_promotion).cycle({fx: 'cover', timeout: 8000});
        }
    }    
}

function init_header_images() {
    if (!($.browser.msie && $.browser.version <= 6)) {
        var $header_images = $('#header_images');
        if ($header_images.length > 0) {
            $('> div', $header_images).wrapAll('<div class="wrapper" style="width:100%; height:100%;" />');
            $('> .wrapper', $header_images).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_form_cookification() {
    /* rf: rewrite the cookify function from cookies to only use id as its key and group them all together in dictionary of form_id */
    $.fn['cookifyFormfield'] = function(form_id) {
        form_cookie = $.cookies.get(form_id);
        if (!form_cookie) {
            form_cookie = {}
        }
        return this.each(function() {
            var $this = $(this), name = $this.attr('id'), value;
            if ($this.is( ':checkbox, :radio' )) {
                if($this.attr('checked')) {
                    value = $this.val();
                }
            } else if ($this.is(':input')) {
                value = $this.val();
            } else {
                value = $this.html();
            }

            if( typeof value !== 'string' || value === '' ) {
                value = null;
            }
            form_cookie[name] = value;
            $.cookies.set(form_id, form_cookie);
        });
    }

    cookieFillform = function(form_id) {
        form_cookie = $.cookies.get(form_id);
        if (form_cookie) {
            $.each(form_cookie, function(key, value) {
                $field = $('#' + key);
                if (value !== null) {
                    if ($field.is(':checkbox, :radio')) {
                        if ($field.val() === value) {
                            $field.attr('checked', 'checked');
                            var container = $field.parentsUntil('div.formfield-input-checkbox').parent();
                            container.addClass('active');
                        } else {
                            $field.removeAttr('checked');
                        }
                    } else if ($field.is(':input')) {
                        $field.val(value);
                    } else {
                        $field.html(value);
                    }
                }
            });
        }
    }
}

$(function() {
    init_form_cookification();
    init_formfields();
    init_formbuttons();
    init_body_search();
    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();
});
