$(document).click(function(event) { 
    if($(event.target).parents().index($('.pop-1')) == -1) {
        if($('.pop-1').is(":visible")) {
            $('.pop-1').hide();
        }
    }   
    
});
$(function() {

    $("#subscription-popup-close").click(function () {

        $.dimOut();
        $("#subscription-popup").fadeOut();
        return false;

    });

    $("#btn-subscribe-detail").click(function () {

        var email_address = $("#subscription-email-2").val();

        if (!validate_email(email_address)) {
            $.alert($(this).attr('data:fail'));
            return false;
        }

        var groups = [];
        $(".subscription-groups:checked").each(function () {
            groups.push($(this).val());
        });

//        if (groups.length > 0) {

            $.post('/', {
                ajax: true,
                email: email_address,
                all: groups.join(','),
                action: 'subscribe',
                language: LANG
            }, function (data) {
                $("#subscription-popup").fadeOut(400, function () {
                    eval(data);
                });
            });

/*
        } else {

            var text_choose = $(this).attr('data:choose');

            $("#subscription-popup").fadeOut(function () {
                $.alert(text_choose);
            });

        } */

        return false;

    });
    
    $("#flash-filter").bind('change keyup', function () {
        
        var map = $("#panorama-map")[0];
        var cat_id = $(this).val();
        
        if (cat_id == 0) {
            if (typeof map.markByCategory == "function") {
                map.unmarkAll();
            }            
        } else {
            if (typeof map.markByCategory == "function") {
                map.markByCategory(cat_id);
            }
        }
        
    });

    $("#btn-subscribe").click(function () {

        var email_address = $("#subscription-email").val();

        if (!validate_email(email_address)) {
            $.alert($(this).attr('data:fail'));
            return false;
        }

        $.post('/', {
                ajax: true,
                email: email_address,
                all: '',
                action: 'subscribe',
                language: LANG
            }, function (data) {
                eval(data);
            });

        return false;

        $("#subscription-email-2").val($("#subscription-email").val());
        $.dimIn({}, null, function () {
            $("#subscription-popup-close").fadeOut();
        });
        $("#subscription-popup").center().fadeIn();

        return false;

    });

    $("#subscription-email").defaultText();
    $("#search-box-top").defaultText();
    $("#search-box-bottom").defaultText();

    var cache = {};
    var search_delay = 0;
    $("#search-box-top").bind('change keyup', function (event) {
        // 40 - down
        // 38 - up
        if (event.keyCode == '27') {
            $("#wrap-search-box-popup").hide();
            return false;
        }
        if (event.keyCode == '13') {
            $act = $("#wrap-search-box-popup").find('.act');
            if ($act.length > 0) {
                $(this).val($act.html());
                event.preventDefault();
                document.location = $act.attr('href');
                return false;
            }
        }
        if ((event.keyCode == '40') || (event.keyCode == '38')) {
            $act = $("#wrap-search-box-popup").find('.act');
            if ($act.length > 0) {
                $next = event.keyCode == '40' ? $act.parent().next() : $act.parent().prev();
                $act.removeClass('act');
                if ($next.length > 0) {
                    $next.children('a').addClass('act');
                } else {
                    if (event.keyCode == '40') {
                        $("#wrap-search-box-popup").find('a:first').addClass('act');
                    } else {
                        $("#wrap-search-box-popup").find('a:last').addClass('act');
                    }
                }
            } else {
                if (event.keyCode == '40') {
                    $("#wrap-search-box-popup").find('a:first').addClass('act');
                } else {
                    $("#wrap-search-box-popup").find('a:last').addClass('act');
                }
            }
            return false;
        }
        clearTimeout(search_delay);
        var $t = $(this);
        var term = $t.val();
        if (term.length < 2) {
            $("#wrap-search-box-popup").hide();
        } else {
            search_delay = setTimeout(function () {
                if (cache[term] != undefined) {
                    response(cache[term]);
                } else {
                    $.getJSON('/', { ajax: true, action: 'search', lang: LANG, 'term': term }, function (data) {
                        cache[term] = data;
                        response(data);
                    });
                }
            }, 100);
        }
    });

    function response(data) {

        var $p = $("#wrap-search-box-popup");

        if (data.length == 0) {
            $p.hide();
            return false;
        }

        var $list = $p.find('ul');
        var html = '';
        var pattern = '<li><a href="LINK">TITLE</a></li>';
        $.each(data, function (i) {
            html += pattern.replace('LINK', '/' + this.value).replace('TITLE', this.label);
        });
        $list.html(html);
        $p.show();

    }

    $("#top-nav > li").hover(function () {
        $(this).children('a').addClass('hover');
    }, function () {
        $(this).children('a').removeClass('hover');
    });

    $("#category-switcher").change(function () {

        document.location = window.catalog_base + $(this).val();

    });

    $(".show-akcijos").toggle(function () {

        $(this).closest('li').addClass('opened');
        $(this).parent().addClass('botomas-act');
        $(this).addClass('akcijos-act').parent().parent().find('.offers').show();

    }, function () {

        $(this).closest('li').removeClass('opened');
        $(this).parent().removeClass('botomas-act');
        $(this).removeClass('akcijos-act').parent().parent().find('.offers').hide();

    });
    
    
    
    /*$('.show-offer').toggle(function() {
    //alert($(this).parent().next('.pop-1').attr('id'));
        $(this).parent().next('.pop-1').show();
    }, function () {
        $(this).parent().next('.pop-1').hide();
    });*/

    $('.show-offer').live('click', function() {
        $('.listas-1').find('.pop-1').hide();   
        $(this).parent().next('.pop-1').show();
        return false;
    });

    $homepage_tabs = $("#homepage-tabs");

    if ($homepage_tabs.length > 0) {

        var lock_tabs = false;

        $homepage_tabs.find('a')
            .each(function () {
                var $t = $(this);
                if ($t.attr('data:image') != undefined) {
                    var img = new Image();
                    img.src = $t.attr('data:image');
                }
            })
            .click(function (e, custom) {

                if (custom == undefined) {
                    clearInterval(homepage_animation);
                }

                if (lock_tabs) {
                    return false;
                }

                lock_tabs = true;

                var $t = $(this);
                if ($t.is('.act')) return false;

                var $act = $homepage_tabs.find('.act');

                $("#splash-preview").find('a').attr('href', $t.attr('href'));

                var image = new Image();
                $(image).load(function () {
                    $("#splash-preview").find('img').fadeOver(700, function () {
                        lock_tabs = false;
                    }, {}, {
                        src: $t.attr('data:image')
                    });
                })
                image.src = $t.attr('data:image');

                $act.animate({
                    height: 47
                }, 500);

                $act.removeClass('act');

                $t.animate({
                    height: 57
                }, 500);

                $t.addClass('act');

                return false;
        });

        var homepage_animation = setInterval(function () {

            var $new_item = $homepage_tabs.find('.act').parent().next();

            if ($new_item.length == 0) {
                $new_item = $homepage_tabs.find('li:first');
            }

            $new_item.children('a').trigger('click', ['fake']);

        }, 5000);

    }

    $gallery = $("#gallery");

    if ($gallery.length > 0) {

        $gallery_popup = $("#popup-preview");
        $gallery_popup.find('.close-1').click(function () {
            $gallery.find('.act').removeClass('act');
            $gallery_popup.fadeOut(400);
            $.dimOut();
            return false;
        });

        $gallery_popup.find('.next').click(function () {

            var $new_act = $gallery.find('.act').removeClass('act').parent().next().children('a').addClass('act');

            $gallery_popup.find('img').attr('src', $new_act.attr('href'));

            if ($new_act.parent().next().length == 0) {
                $(this).hide();
            }

            $gallery_popup.find('.prev').show();

            $("#popup-preview-current").html($new_act.parent().prevAll().length + 1);
            return false;
        });

        $gallery_popup.find('.prev').click(function () {

            var $new_act = $gallery.find('.act').removeClass('act').parent().prev().children('a').addClass('act');

            $gallery_popup.find('img').attr('src', $new_act.attr('href'));

            if ($new_act.parent().prev().length == 0) {
                $(this).hide();
            }

            $gallery_popup.find('.next').show();

            $("#popup-preview-current").html($new_act.parent().prevAll().length + 1);
            return false;
        });

        $gallery.find('.thumb-list a').click(function () {

            $(this).addClass('act');
            
            if ($(this).parent().prev().length > 0) {
                $gallery_popup.find('.prev').show();
            } else {
                $gallery_popup.find('.prev').hide();
            }

            if ($(this).parent().next().length > 0) {
                $gallery_popup.find('.next').show();
            } else {
                $gallery_popup.find('.next').hide();
            }

            $("#popup-preview-total").html($(this).parent().parent().children().length);
            $("#popup-preview-current").html($(this).parent().prevAll().length + 1);

            $gallery_popup.find('img').attr('src', $(this).attr('href'));
            $.dimIn({}, null, function () {
                $gallery_popup.find('.close-1').click();
            });
            $gallery_popup.center().fadeIn(400);

            return false;

        });

    }

});

jQuery.extend({
    slide: function($container, child_element_no, callback) {
        var $slider = $container.children(":first");
        var new_offset = $slider.children(':eq('+child_element_no+')').offset().left - $container.offset().left - ($slider.offset().left - $container.offset().left);
        $slider.animate( {left: -1 * new_offset}, 600, 'easeOutQuad', callback);
        return this;
    },
    slide_page: function($container, page_no, size, callback) {
        if (typeof(size) == 'undefined') {
            size = parseInt($container.parent().css('width').match(/\d+/));
        }
        var new_offset = size * page_no;
        $container.animate( {left: -1 * new_offset}, 600, 'easeOutQuad', callback);
        return this;
    },
    imgLoad: function(src, loaded_callback) {
        var img = new Image();
        $(img).load( function () {
            loaded_callback(img);
        });
        img.src = src;
        return this;
    },
    dimIn: function (user_css, callback, on_click) {
        $dim = $("#dim");
        if ($dim.length == 0) {
            $dim = $("<div />").attr('id', 'dim').css(
                { position: 'absolute',
                  top: 0,
                  left: 0,
                  width: '100%',
                  height: $(document).height(),
                  zIndex: 20,
                  background: '#333',
                  opacity: .8 });
            $('body').prepend($dim);
        }
        
        window.dim_height = $(document).height();
        window.dim_height_int = setInterval(function () {
            if (window.dim_height != $(document).height()) {
                window.dim_height = $(document).height();
                $dim.css('height', window.dim_height);
            }
        }, 100);
        
        if (on_click != undefined) {
            $dim.click(on_click);
        }
        if ($dim.data('act') == true) return false;
        if (user_css != undefined) {
            $dim.css(user_css);
        }
        return $dim.data('act', true).fadeIn(400, callback);
    },
    dimOut: function (callback) {
        $dim = $("#dim").unbind('click');
        if ($dim.data('act') == true) {
            $dim.fadeOut(400, callback).data('act', false);
        }
        clearInterval(window.dim_height_int);
    },
    alert: function (message) {
        $.dimIn({}, null, function () {
            window.alert_box.fadeOut();
            $.dimOut();
        });
        if (window.alert_box == undefined) {
            window.alert_box = $('<div style="width: 400px; z-index:99999999; display: none; cursor: pointer; position: absolute; padding: 10px; background: #fff; box-shadow: 0 0 5px #666; -moz-box-shadow: 0 0 5px #666; -webkit-box-shadow: 0 0 5px #666;" />').appendTo('body').click( function () {
                $(this).fadeOut();
                $.dimOut();
            } );
        }
        window.alert_box.html('<p style="display: block; text-align: left;">'+message+'</p>').center().fadeIn();
    }
});

jQuery.fn.extend({
    defaultText: function () {
        var $t = this;
        $t.click(function() {
            if ($t.data('default-text') == undefined) {
                $t.data('default-text', $t.val());
            }
            if ($t.val() == $t.data('default-text')) {
                $t.val('');
            }
        });
        $t.blur(function () {
            if (($t.val() == '') && ($t.data('default-text') != undefined)) {
                $t.val($t.data('default-text'));
            }
        });
    },
    center: function () {
        this.css( { position: 'absolute',
                    top: $(document).scrollTop() + (Math.ceil($(window).height()) - this.height()) / 2,
                    left: '50%',
                    marginLeft: -1 * Math.ceil(this.width() / 2) } );

        return this;
    },
	fadeOver: function (speed, callback, css, attr) {
        var $t = this;
		c = $t.clone();
		c.css( { position: 'absolute',
                 width: $t.width(),
                 height: $t.height(),
                 display: 'none',
                 zIndex: 2 } );
                if (css != undefined) {
                    c.css(css);
                }
                if (attr != undefined) {
                    c.attr(attr);
                }
                $tp = $t.parent(); // container
		$tp.css( { width: $tp.width(),
                   height: $tp.height()} );

		c.insertBefore($t).fadeTo(speed, 1, function () {
			c.next().remove();
			c.css( { position: 'relative', zIndex: 1} );
			if (typeof(callback) == 'function') callback();
		});
        return $t;
	}
});

function validate_email(email) {
    var filter = /^([a-zA-Z0-9_.-])+@(([a-zA-Z0-9-])+.)+([a-zA-Z0-9]{2,4})+$/;
    return filter.test(email);
}

function popup(url) {

    if (typeof(window.popuped) == 'undefined') {
        window.popuped = $('<div style="z-index:99999999; display: none; cursor: pointer; position: absolute; padding: 7px; background: #ffffff; box-shadow: 0 0 5px #666; -moz-box-shadow: 0 0 5px #666; -webkit-box-shadow: 0 0 5px #666;" />').appendTo('body').click( function () {
            $(this).find('img').fadeOut(400).end().fadeOut(400);
            $.dimOut();
        } );
        $('<img style="display: none" />').appendTo(window.popuped);
    }

    $popuped = window.popuped;

    $.dimIn({}, null, function () {
        window.popuped.click();
    });

    var props = {width: 100,
                  height: 100,
                  left: Math.ceil($(window).width() / 2) - 50,
                  top: $(document).scrollTop() + Math.ceil(($(window).height() - 25) / 2) - 20};

    if ($popuped.css('display') == 'none') {
        $popuped.css(props);
    } else {
        $popuped.find('img').fadeOut(400);
    }

    var img = new Image();

    $popuped.fadeIn(400);

    $(img).load( function () {

        $popuped.find('img').attr('src', img.src).end().animate(
            {
                left: Math.ceil(($(window).width() - img.width) / 2),
                top: (($(window).height() - img.height) / 2) + $(document).scrollTop(),
                height: img.height,
                width: img.width
            }, 400, function () {
                $(this).find('img').fadeIn('fast');
            }
        );


    });

    img.src = url;

}
