jQuery.exists = function(selector) {
    return ($(selector).length > 0);
}

jQuery.fn.center = function (absolute) {
    return this.each(function () {
        var t = jQuery(this);
        t.css({
            position:     'absolute',
            left:        '50%',
            top:        '50%',
            zIndex:        '1000'
        }).css({
            marginLeft:    '-' + (t.outerWidth() / 2) + 'px',
            marginTop:    '-' + (t.outerHeight() / 2) + 'px'
        });

        if (absolute) {
            t.css({
                marginTop:    parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(),
                marginLeft:    parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
            });
        }
    });
};

//dimScreen()
//by Brandon Goldman
jQuery.extend({
    //dims the screen
    dimScreen: function(speed, opacity, callback) {
        if(jQuery('#__dimScreen').size() > 0) return;
		
        if(typeof speed == 'function') {
            callback = speed;
            speed = null;
        }

        if(typeof opacity == 'function') {
            callback = opacity;
            opacity = null;
        }

        if(speed < 1) {
            var placeholder = opacity;
            opacity = speed;
            speed = placeholder;
        }
		
        if(opacity >= 1) {
            var placeholder = speed;
            speed = opacity;
            opacity = placeholder;
        }

        speed = (speed > 0) ? speed : 500;
        opacity = (opacity > 0) ? opacity : 0.5;
        return jQuery('<div></div>').attr({
            id: '__dimScreen'
            ,
            fade_opacity: opacity
            ,
            speed: speed
        }).css({
            background: '#000'
            ,
            height: $(document).height() + "px"
            ,
            left: '0px'
            ,
            opacity: 0
            ,
            position: 'absolute'
            ,
            top: '0px'
            ,
            width: '100%'
            ,
            zIndex: 10
        }).appendTo(document.body).fadeTo(speed, opacity, callback);
    },
	
    //stops current dimming of the screen
    dimScreenStop: function(callback) {
        var x = jQuery('#__dimScreen');
        var opacity = x.attr('fade_opacity');
        var speed = x.attr('speed');
        x.fadeOut(speed, function() {
            x.remove();
            if(typeof callback == 'function') callback();
        });
    }
});

function sendToFriend()
{
    $.dimScreen(300, 0.7, function() {
        $("#js_sendfriend").center().show();
        genCaptcha();
        return false;
    });
}

function sendToFriendSubmit()
{
    $("#js_send_button").fadeOut("fast");
    ajax_url = ajax_path + "sendtofriend/";
    $.post(ajax_url,
    {
        path: $("#js_path").val(),
        name: $("#js_name").val(),
        email: $("#js_email").val(),
        friend1: $("#js_friend1").val(),
        friend2: $("#js_friend2").val(),
        friend3: $("#js_friend3").val()
    //captcha: $("#js_captcha").val()
    },
    function(result){
        $("#js_send_button").fadeIn("fast");
        success = true;
        if (typeof(result)=="object"){
            if (result.error == 'mail_error'){
                $("#js_send_error").show();
            } else {
                $("#js_send_error").hide();
            }
            $.each(result.status, function(field, status){
                if (status!="ok"){
                    success = false;
                    if (field == 'captcha' && status == 'validate') {
                        $("#js_" + field + "_label").hide();
                        $("#js_" + field + "_label_wrong").show();
                    }
                    $("#js_" + field + "_label").css('color', 'red');
                } else {
                    $("#js_" + field + "_label").css('color', 'black');
                }
            });
            if (success && result.returnhtml){
                $("#js_sendtofriend_content").html(result.returnhtml);
            }
        }
    },
    "json"
    );
}

function genCaptcha()
{

    $('#js_captcha_img').attr('src', root_path + '/_cms/captcha/?fkasj=' + Math.floor(Math.random()*11));
    return false;

}

function getCalendar(year, month)
{
    var id = $("#js_calendar_id").val();
    $("#js_calendar").html('<img src="' + root_path + '/gfx/ajax-loader.gif" class="ajaxloader" />');
    $.ajax({
        url: ajax_path + "calendar/id/" + id + "/_year/" + parseInt(year) + "/_month/" + parseInt(month),
        cache: false,
        success: function(html){
            $("#js_calendar").html(html);
        }
    });
}


function showTableInfo(id)
{
    var offset = $("#js_table_info_link_" + id).position();
    if ($.browser.msie && parseInt($.browser.version) < 7){
        $("#js_row_info_" + id).css("left", (offset["left"] - 5) + "px");
        $("#js_row_info_" + id).css("top", (offset["top"] - 385) + "px");
    } else {
        $("#js_row_info_" + id).css("left", (offset["left"] + 260) + "px");
        $("#js_row_info_" + id).css("top", (offset["top"]) + "px");
    }
    $("#js_row_info_" + id).show("fast");

}

function hideTableInfo(id)
{
    $("#js_row_info_" + id).animate({
        opacity: 1.0
    }, 250, function(){
        $(this).hide("fast");
    });
	
}

function doSearch() 
{
    query = $("input#js_search").val();
    if (query.length>1) {
        query = encodeURI(query);
        query = query.replace(/\//g, "-fs-");
        query = query.replace(/\./g, "-dot-");
        window.location = root_path + ((pathname.substr(1,3) == "eng" || pathname.substr(1,3) == "rus") ? "/" + pathname.substr(1,3) : "") +  "/_search/" + query;
    }
}

function doLogin()
{
    if ($("#js_username").val() && $("#js_password").val()){
        $.post(
            ajax_path + "userlogin/",
            {
                user: $("#js_username").val(),
                pass: $("#js_password").val()
            },
            function (result){
                if (result == "ok"){
                    window.location = root_path + ((pathname.substr(1,3) == "eng" || pathname.substr(1,3) == "rus") ? "/" + pathname.substr(1,3) : "") +  "/_userarea";
                } else {
                    $("#js_login_error").show();
                }
            }
            );
    }
}
// Created by: Bob Mason :: http://www.omega-cottage.co.uk/WLS

function  calculateBMI() {
    var weight = $('#bi_weight').val();
    var height = $('#bi_height').val();
    var height2 = height / 100
    var BMI = weight  / (height2 * height2)
    $('#bmi_result').html('Sinu kehamassiindeks on <span>'+custRound(BMI,1)+'</span>');
}

function custRound(x,places) {
    return (Math.round(x*Math.pow(10,places)))/Math.pow(10,places)
}

function doLogout()
{
    window.location = root_path + ((pathname.substr(1,3) == "eng" || pathname.substr(1,3) == "rus") ? "/" + pathname.substr(1,3) : "") +  "/_userarea/_logout";
}

$(function(){

    root_path = location.protocol + "//" + location.host;
    ajax_path = root_path + "/_ajax/";
    pathname = location.pathname;
	
	//banner slider
	if ($('#slider').length > 0)
	{
		$('#slider').anythingSlider({
			autoPlay: true,
			delay: 15000,
			pauseOnHover: false,
			onSlideInit: function(slider){

				//reload banners
				$('#slider').find('object').each(function(){
					
					var activePage = $(this).closest('.activePage').attr('class');
					if (activePage == undefined){
					
						var parent = $(this).parent(); 
						var clone = $(this).clone(true);
						$(this).remove();
						parent.append(clone);
					}
					
				});
			}
		});
	}

    if ($.exists("#js_calendar")){

        var path_pieces = pathname.split("/");
        var next = false;
        var year = false;
        var month = false;

        for (var i in path_pieces){
            if (next == "_year"){
                year = parseInt(path_pieces[i]);
            } else if (next == "_month"){
                month = parseInt(path_pieces[i]);
                break;
            }
            next = path_pieces[i];
        }
        getCalendar(year, month);

    }

    if ($.exists("#js_login_form")){
        $("#js_login_form").submit();
    }

    $(".button_info").mouseover(function() {
        id = $(this).attr('id');
        id = id.replace('button_', '');
        $(this).addClass('active');
        offset = $(this).position();
        height = $("#layer_" + id).height();
        //alert(height);
        if ($.browser.msie && parseInt($.browser.version) < 7){
            $("#layer_" + id).css("left", (offset["left"]) + "px");
            $("#layer_" + id).css("top", (offset["top"]-height) + "px");
        } else {
            $("#layer_" + id).css("left", (offset["left"]) + "px");
            $("#layer_" + id).css("top", (offset["top"]-height) + "px");
        }
        $("#layer_" + id).show();

    }).mouseout(function(){
        $(this).removeClass('active');
        $("#layer_" + id).height(height);
        $("#layer_" + id).hide();
    });

    $("input#js_search").bind("keypress", function(e) {
        if (e.keyCode == 13) {
            doSearch();
        }
    });
    $("input#js_password").bind("keypress", function(e) {
        if (e.keyCode == 13) {
            doLogin();
        }
    });
	
});


$(document).ready(function() {
    $('.input').keypress(function(e){
        if(e.which == 13){
            $.post("/_userarea", {
                username: $("form #js_username").attr('value'),
                password: $("form #js_password").attr('value')
            }, first_time=1 );
     
        }
    });
});


