var scripts = document.getElementsByTagName("script");
eval( scripts[ scripts.length - 1 ].innerHTML );
var active_group = 0;

;(function(h){
    var m=h.scrollTo=function(b,c,g){
        h(window).scrollTo(b,c,g)
        };

    m.defaults={
        axis:'y',
        duration:1
    };

    m.window=function(b){
        return h(window).scrollable()
        };

    h.fn.scrollable=function(){
        return this.map(function(){
            var b=this.parentWindow||this.defaultView,c=this.nodeName=='#document'?b.frameElement||b:this,g=c.contentDocument||(c.contentWindow||c).document,i=c.setInterval;
            return c.nodeName=='IFRAME'||i&&h.browser.safari?g.body:i?g.documentElement:this
            })
        };

    h.fn.scrollTo=function(r,j,a){
        if(typeof j=='object'){
            a=j;
            j=0
            }
            if(typeof a=='function')a={
            onAfter:a
        };

        a=h.extend({},m.defaults,a);
        j=j||a.speed||a.duration;
        a.queue=a.queue&&a.axis.length>1;
        if(a.queue)j/=2;
        a.offset=n(a.offset);
        a.over=n(a.over);
        return this.scrollable().each(function(){
            var k=this,o=h(k),d=r,l,e={},p=o.is('html,body');
            switch(typeof d){
                case'number':case'string':
                    if(/^([+-]=)?\d+(px)?$/.test(d)){
                    d=n(d);
                    break
                }
                d=h(d,this);
                case'object':
                    if(d.is||d.style)l=(d=h(d)).offset()
                    }
                    h.each(a.axis.split(''),function(b,c){
                var g=c=='x'?'Left':'Top',i=g.toLowerCase(),f='scroll'+g,s=k[f],t=c=='x'?'Width':'Height',v=t.toLowerCase();
                if(l){
                    e[f]=l[i]+(p?0:s-o.offset()[i]);
                    if(a.margin){
                        e[f]-=parseInt(d.css('margin'+g))||0;
                        e[f]-=parseInt(d.css('border'+g+'Width'))||0
                        }
                        e[f]+=a.offset[i]||0;
                    if(a.over[i])e[f]+=d[v]()*a.over[i]
                        }else e[f]=d[i];
                if(/^\d+$/.test(e[f]))e[f]=e[f]<=0?0:Math.min(e[f],u(t));
                if(!b&&a.queue){
                    if(s!=e[f])q(a.onAfterFirst);
                    delete e[f]
                }
            });
        q(a.onAfter);
            function q(b){
            o.animate(e,j,a.easing,b&&function(){
                b.call(this,r,a)
                })
            };

        function u(b){
            var c='scroll'+b,g=k.ownerDocument;
            return p?Math.max(g.documentElement[c],g.body[c]):k[c]
            }
        }).end()
    };

function n(b){
    return typeof b=='object'?b:{
        top:b,
        left:b
    }
}
})(jQuery);

$(document).ready(function(){

    $("#thumbs .th A").each( function (index) {
			
        $(this).click( function () {
					
            var fn = $(this).attr("href");
            var text = $(this).attr("title");
            var img = new Image();
					
            $("#loading_cont").css("margin-top", Math.round(($("#preview_img").height()) / 2) - 20);
            $("#loading_cont").show();
					
            $(img).load( function () {
											
                document.getElementById('preview_img').src = img.src;
						
                if (img.width >= 300)
                    var aspect = (Math.round(img.height / (img.width / 300)));
                else
                    var aspect = (Math.round(img.height));
						
                $("#contPreview").animate( {
                    height: aspect
                }, 500, function () {
                    $("#preview").show();
                });
						
                $("#preview").unbind().click(function () {
							
                    popup(BASE_HREF + 'assets/scripts/popup.php?imgUrl=../../' + fn);
							
                });
						
                $("#underText").html(text);

                $("#loading_cont").hide();
																	
            });

            $("#contPreview").css("width", $("#preview IMG").width())
            .css("height", $("#preview IMG").height());

            $("#preview").hide();
            img.src = "./assets/image.php?w=300&f=../" + fn;
					
            $("#thumbs .th A").removeClass("act");
            $(this).addClass("act");
												
            return false;

        });
			 	
    }
    );

    $("#btnNext").click( function () {
											
        ++active_group;

        $("#thumbs LI.group-" + (active_group - 1)).fadeOut("fast", function () {
																												  
            $("#btnPrev").removeClass("btnPrev");
													
            $("#thumbs LI.group-" + active_group).fadeIn("fast");

            if ($("#thumbs LI.group-"+(active_group + 1)).length == 0) {
                $("#btnNext").hide();
            }
													
        });
												
												
    });
		
		
    $("#btnPrev").click( function () {

        --active_group;

        $("#thumbs LI.group-" + (active_group + 1)).fadeOut("fast", function () {
																										  
            $("#btnNext").show();
													
            $("#thumbs LI.group-"+(active_group)).fadeIn("fast");

            if ($("#thumbs LI.group-"+(active_group - 1)).length == 0) {
                $("#btnPrev").addClass("btnPrev");
            }
													
        });
											
    });
									   			
    var miniq_text = $("#miniq").val();
	
    $("#miniq").click( function () {
								 
        if ($(this).val() == miniq_text) $(this).val("");
								 
    });
	
    $("#miniq").blur( function () {
								 
        if ($(this).val() == "") {
			
            if ($(this).hasClass("searched")) return false;
			
            $(this).val(miniq_text);
			
        }
								 
    });
	
    $("#closeRecommend").click( function () {
        $(this).parent().fadeOut("fast", function () {
            $.dimOut();
            $("#blank").hide();
            $("#recComment").val("");
        } );
    } );
	
    $(".btnRecommend").click( function () {
										
        var id = String($(this).attr("href")).match(/\d+/);
        if (id.length == 0) {
            return false;
        }
        id = id[0];

        $("#recArticleId").val(id);
        $.dimIn({}, function () {
            $("#recommend").center().fadeIn("fast");
        }, function () {
            $.dimOut();
            $("#recommend").fadeOut();
        })

        return false;
		
    });
	
    $(".openpopup").click( function () {
					
        var top = $(document).scrollTop() + 50;
        var left = ($(document).width() - 640) / 2;
        $("#popup-" + $(this).attr("lang")).css("top", top).css("left", left).fadeIn("fast");
		
        return false;

    });
	
	
    $("#from_year").change( function () {
									  
        $.post('./ajax/calendar.php', {
            y: $("#from_year").val(),
            m: $("#from_month").val(),
            type: "from",
            dt: $("#from").val()
        }, function (data) {
			
            $("#from_cal").html(data);
            bindTillDay();
            bindFromDay();
			
        });
									  
    });
	
    $("#from_month").change( function () {
									  
        $.post('./ajax/calendar.php', {
            y: $("#from_year").val(),
            m: $("#from_month").val(),
            type: "from",
            dt: $("#from").val()
        }, function (data) {
			
            $("#from_cal").html(data);
            bindTillDay();
            bindFromDay();
			
        });
									  
    });
	
    $("#till_year").change( function () {
									  
        $.post('./ajax/calendar.php', {
            y: $("#till_year").val(),
            m: $("#till_month").val(),
            type: "till",
            dt: $("#till").val()
        }, function (data) {
			
            $("#till_cal").html(data);
            bindTillDay();
            bindFromDay();
			
        });
									  
    });
	
    $("#till_month").change( function () {

        $.post('./ajax/calendar.php', {
            y: $("#till_year").val(),
            m: $("#till_month").val(),
            type: "till",
            dt: $("#till").val()
        }, function (data) {
			
            $("#till_cal").html(data);
            bindTillDay();
            bindFromDay();
			
        });
									  
    });
	
    function bindTillDay() {
		
        $(".till_day").click( function () {
			
            $(".till_day").parent().removeClass("act");
            $(this).parent().addClass("act");
			
            var t = new String($("#till").val());
            t = t.substr(0, 8);
            var v = $(this).html();
            if (v.length == 1) v = '0' + v;
            $("#till").val(t + v);
			
            t = new String($("#till_date").val());
            $("#till_date").val((t.substring(0, t.indexOf('/') + 2) + v + ' d.'));
			
            return false;
										
        });
		
    }
	
    function bindFromDay() {
		
        $(".from_day").click( function () {
					
            $(".from_day").parent().removeClass("act");
            $(this).parent().addClass("act");
			
            var t = new String($("#from").val());
            t = t.substr(0, 8);
            var v = $(this).html();
            if (v.length == 1) v = '0' + v;
            $("#from").val(t + v);
			
            t = new String($("#from_date").val());
            $("#from_date").val((t.substring(0, t.indexOf('/') + 2) + v + ' d.'));
			
            return false;
										
        });
		
    }
	
    bindTillDay();
    bindFromDay();
	
    $(".btnClosePopup").click( function () {
		
        $(this).parent().parent().hide();
		
    });
	
    $(".enlarge").click( function () {

        var cont = $(this).parent().parent().parent();

        var loader = new Image();
		
        $("#loadings-" + $(cont).attr("lang")).show();

        $(loader).load( function () {
			
            $(".loadings").hide();
            $("#preview-" + $(cont).attr("lang")).attr("src", loader.src);
			
			
        });
		
        loader.src = $(this).attr("name");
		
		
        return false;
		
    });

    $("#staff_list UL LI A").click( function () {
		
        var img = new Image();
        var email = $(this).attr("title");
        var phone = $(this).attr("phone");
        var phone_work = $(this).attr("phonework");

        $("#staff_list UL > LI").removeClass("act");
        $(this).parent().addClass("act");
		
        $(img).load( function () {
			
            $("#staff_preview_phone").fadeOut("fast");
            $("#staff_preview_phone_work").fadeOut("fast");
            $("#staff_preview_email").fadeOut("fast");
			
            $("#staff_preview_image").fadeOut("fast", function () {
																
                document.getElementById('staff_preview_image').src = img.src;
                $(this).fadeIn("fast");

                $("#staff_preview_phone").html(phone).fadeIn("fast");
                $("#staff_preview_phone_work").html(phone_work).fadeIn("fast");
                $("#staff_preview_email").attr("href", "mailto:"+email).html(email).fadeIn("fast");

            });
							   
        });
		
        img.src = $(this).attr("href");
		
        if ($(document).scrollTop() > $("#staff_preview_image").offset().top) {
            $(document).scrollTo($("#staff_preview_image").offset().top - 40, 400);
        }
		
        return false;
		
    });
	  
    $("#btnSendRecommendation").click( function () {
	 	
        $("#recommend LABEL").removeClass("red");
		  
        $.post( BASE_HREF + 'ajax/recommend.php',
        {
            recName: $("#recName").val(),
            recEmail: $("#recEmail").val(),
            lng: LANG,
            recComment: $("#recComment").val(),
            recArticleId: $("#recArticleId").val()
        },
        function (data) {
            $.dimOut();
            eval(data);
        });
								 
    });
		
    $("A[href='#']").attr("href", "javascript:void(0)");
	
    $("#btnPrint").click( function () {
        printpage()
    } );

    if (doScroll != '') {
        $.scrollTo(doScroll, 400);
    }
	
    $(".gotoNewForum").click( function () {
        $.scrollTo("#contNewForum", 400);
        return false;
    });
	
    $("#formComment").submit(function () {
		
        var allowSubmit = true;
        $("#formComment *").removeClass("remove");
									   
        if (document.getElementById('agree').checked == false) {
            $("#agree").parent().children("label").addClass("remove");
            allowSubmit = false;
        }
		
        if ($("#title").val() == '') {
            $("#title").addClass("remove");
            allowSubmit = false;
        }
		
        if ($("#comment").val() == '') {
            $("#comment").addClass("remove");
            allowSubmit = false;
        }
		
        if (allowSubmit) return true;
        else return false;
									   
    });

    $("#formForum").submit(function () {
		
        var allowSubmit = true;
        $("#formForum *").removeClass("remove");
									   
        if (document.getElementById('agree').checked == false) {
            $("#agree").parent().children("label").addClass("remove");
            allowSubmit = false;
        }
		
        if ($("#title").val() == '') {
            $("#title").addClass("remove");
            allowSubmit = false;
        }
		
        if ($("#name").val() == '') {
            $("#name").addClass("remove");
            allowSubmit = false;
        }
		
        if ($("#content").val() == '') {
            $("#content").addClass("remove");
            allowSubmit = false;
        }
		
        if (allowSubmit) return true;
        else return false;
									   
    });

    $(".wrap-rate").each(function () {
        var $t = $(this);
        $t.data('restore', $t.find('.off').length);
    }).hover(function () {
        
    }, function () {
        var $t = $(this);
        if ($t.hasClass('voted')) {
            return;
        }
        var c = $t.data('restore');
        $t.find('a').each(function (i) {
            i + c >= 5 ? $(this).addClass('off') : $(this).removeClass('off');
        })
    });

    $(".wrap-rate a").hover(function () {

        var $t = $(this);
        var $p = $t.parent();

        if ($p.hasClass('voted')) {
            return;
        }

        $p.find('a').removeClass('off');
        $t.nextAll().addClass('off');

    }, function () {



    }).click(function () {

        var $t = $(this);
        var $p = $t.parent();
        
        if ($p.is('.voted')) {
            return false;
        }
        
        var rating = $t.prevAll().length + 1;
        $p.data('restore', 5 - rating);

        var $votes = $p.addClass('voted').parent().find('span');
        
        if ($votes.length > 0) {
            var num = parseInt(String($votes.html()).match(/\d+/)[0]);
            $votes.html(String($votes.html()).replace(/\d+/, num + 1));
        }

        $.post('/ajax/rate.php', {
            id: $p.attr('data:id'),
            type: $p.attr('data:type'),
            vote: rating
        }, function (data) {

            $p.find('a').each(function (i) {
                i + 1 > data ? $(this).addClass('off') : $(this).removeClass('off');
            })

        });

    });
	
});

function printpage() {
    var url = document.location.href;
	
    for (i = url.length; i > 0; i--) {
        if (url.charAt(i) == '?') {
            url = url + '&';
            break;
        } else if ((url.charAt(i) == '/') || (url.charAt(i) == '\\')) {
            url = url + '?';
            break;
        }
    } // pridet ? jei nera paramu, pridet & jei yra paramu

    win = window.open(url + 'do=print', 'popup', 'toolbar = 0, scrollbars = 1, status = 0');
    win.window.print();
}

function popup(url) {
    win = window.open(url, 'popup', 'width = 50, height = 50, toolbar = 0, scrollbars = 1, status = 0');
    return false;
}

function orderSubmit() {

    $(".warn").fadeOut("fast");

    $.post('./ajax/order.php',
    {
        type : $("#subscriber").val(),
        dt: $("#day").val() + ' ' + $("#month").val() + ' ' + $("#year").val(),
        duration: $("#duration").val(),
        price: $("#price").html(),
        full_name: $("#full_name").val(),
        email: $("#email").val(),
        position: $("#position").val(),
        elpastas: $("#elpastas").val(),
        phone: $("#phone").val(),
        fax: $("#fax").val(),
        company: $("#company").val(),
        company_type: $("#company_type").val(),
        company_code: $("#code").val(),
        address: $("#address").val(),
        comments: $("#comments").val()
    }, function (data) {
				 
        if (data == '') {
            return true;
        }
			   
        eval(data);
    });
	
    return false;
	
};

function makehomepage() {

    if (navigator.appName.indexOf('Microsoft') != -1) {
        document.body.style.behavior='url(#default#homepage)';
        document.body.setHomePage('http://www.grokiskis.lt');
    } else if (navigator.appName.indexOf('Netscape') != -1) {
        var msg = "Norėdami padaryti grokiskis.lt pirmuoju puslapiu, nutempkite šalia http://www.grokiskis.lt adreso esantį GR logotipą ant kairėje esančio \"Namelio\"";
        alert(msg);
    } else if (navigator.appName.indexOf('Opera') != -1) {
        var msg = "Norėdami padaryti grokiskis.lt pirmuoju puslapiu, eikite į Tools/Preferences/General ir paspauskite \"Use current\" mygtuką.";
        alert(msg);
    } else {
        var msg = "Jūsų naršyklė draudžia automatinį titulinio puslapio pakeitimą. Pakeisti savo pirmąjį puslapį galite savo naršyklės nustatymose";
        alert(msg);
    }
	
};

function init_comment_reporting(t) {
    t = t == undefined ? '' : t;
    $(".report").unbind('click').click(function () {
        var $t = $(this);
        if ($t.data('reported') == true) {
            return false;
        }
        $t.data('reported', true);
        $.post('/ajax/report.php',
        {
            comment_id: String($t.attr('id')).match(/\d+/g)[0],
            type: t
        },
        function (data) {
            if (data == 'hide') {
                $t.closest('li').hide();
            } else {
                $t.html('Dėkojame už bendradarbiavimą');
            }
        }
        );
    });
}


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: 1000,
                  background: '#333',
                  opacity: .8 });
            $('body').prepend($dim);
        }
        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);
        }
    },
    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;
	}
});

