function getFormValues(form_obj)
{
    values = {};

    form_obj.find("input:text, input:password, select").each(function() {
        values[$(this).attr('id')] = $(this).val();
    });

    return values;
}



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


function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}

function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}

function rtrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
}




function confirmAndDelete(href, query) {
    if (!query)
        var query = "Вы действительно хотите удалить запись?";

    if (!confirm(query))
        return;

    document.location.href = href;
}


function ucfirst(str) {
    var f = str.charAt(0).toUpperCase();
    return f + str.substr(1, str.length-1);
}



function reload_page() {
    document.location = document.location.href;
}


function send_confirmation_letter(email) {

    if (email && email.length) {

        if (!email_valid(email)) {
            alert("Введен некорректный Email.");
            return false;
        }

        $.post("/module/users/index/send-confirmation-letter", {email: email}, function(confirmation_result_code) {
            if (confirmation_result_code == "" || confirmation_result_code == "success")
                alert("Письмо отправлено на email '" + email + "'");
            else
                alert(confirmation_result_code);
        });
    }

    return null;
}


function get_comments_block(item_id, item_type, target_id)
{
    var href = "/module/comments/index/index";
    
    $.post(href, {item_id: item_id, item_type: item_type, ajax_get_form: true}, function(results) {
        $(target_id).html(results);
    });
}

function get_likes_block(item_id, item_type, target_id)
{
    var href = "/module/likes/index/get-likes-block";

    $.post(href, {item_id: item_id, item_type: item_type, ajax_get_form: true}, function(results)
    {
        $(target_id).html(results);

        initLikesLinks(target_id);
    });
}

function get_wedding_ready_box()
{
    if ($('#wedding_ready_box_holder').length)
    {
        $.post('/module/weddings/index/get-ready-box', function(data)
        {
            $('#wedding_ready_box_holder').html(data);
        });
    }
}

/*
 * Возвращает объект с абсолютной позицией элемента (.left, .top, .width, .height)
 */
function getElementPosition(elem)
{
    var w = elem.offsetWidth;
    var h = elem.offsetHeight;
    var l = 0;
    var t = 0;

    while (elem){
        l += elem.offsetLeft;
        t += elem.offsetTop;
        elem = elem.offsetParent;
    }

    return {"left":l, "top":t, "width": w, "height":h};
}

var $waitBlock;
var waitsAr = new Array();
$.fn.setLoading = function (open)
{
    if (open!==false) open = true;

    var $wait;
    var waitId = this.attr('waitId');
    if (waitsAr[waitId]) $wait = waitsAr[waitId];
    if (open)
    {
        /* если нет тени - создаём её */
        if (!$wait)
        {
            /* если нет базового блока тени - создаём его */
            if (!$waitBlock)
            {
                var waitBlock = '<div id="wait" style="z-index:999999999;left:0px;top:0px;width:100%;height:100%;display:none;position:absolute;background-color:#ffffff;"></div>';

                $('body:first').append(waitBlock);
                $waitBlock = $('div#wait').css({opacity:0.5});
            }

            /* клонируем базовую тень */
            $wait = $waitBlock.clone().appendTo('body');
            if (!waitId) waitId = waitsAr.length + 1;
            /* добавляем в кэш */
            waitsAr[waitId] = $wait;
            /* добавляем идентификатор в базовый объект */
            this.attr('waitId', waitId);
        }
        /*
        var position = this.position();
        $wait.css({top:position.top, left:position.left, height:this.height(), width:this.width()});
        */
        var position = getElementPosition(this[0]);
        $wait.css({top:position.top, left:position.left, height:position.height, width:position.width});
        $wait.stop().fadeIn();
    } else {
        $wait.stop().fadeOut();
    }
    return this;
}








function get_random_array(length) {
    if (!length)
        length = 10;

    var r = {};

    for (var i = 0; i < length; i++) {
        r[i] = {
            "id" : parseInt(100 * Math.random()),
            "tx" : "element " + i
        };
    }

    return r;
}

function print_r(a, prefix) {
    if (prefix == undefined)
        prefix = "";

    var s = "";
    for (var i in a) {
        if ((a[i] instanceof Array) || (a[i] instanceof Object)) {
            s += prefix + "[" + i + "] - " + (typeof a) + " - {\n";
            s += print_r(a[i], prefix + "\t");
            s += "}\n";
        }
        else
            s += prefix + "[" + i + "] = " + a[i] + "\n";
    }
    return s;
}

// быстрая сортировка массива по ключу ckey
function quickSortByKey(a, ckey, low, hight) {

    this.swap_elements = function(from, to) {
        var i = a[from];
        a[from] = a[to];
        a[to] = i;
    };

    this.array_length = function(a) {
        var result = 0;
        for (var i in a) {
            result++;
        }
        return result;
    };

    if (low == undefined)
        low = 0;

    if (hight == undefined)
        hight = this.array_length(a) - 1;

    this.sort = function(a, ckey, low, hight) {
        if (hight - low <= 0)
            return a;

        if (hight - low == 1) {
            if (a[low][ckey] > a[hight][ckey])
                this.swap_elements(low, hight);

            return a;
        }


        var middle = parseInt((low + hight) / 2);
        var middle_key = a[middle];

        this.swap_elements(middle, low);

        var scan_up = low + 1;
        var scan_down = hight;

        do
        {
            while (scan_up < scan_down && a[scan_up][ckey] <= middle_key[ckey])
                scan_up++;

            while (a[scan_down][ckey] > middle_key[ckey])
                scan_down--;

            if (scan_up < scan_down) {
                this.swap_elements(scan_up, scan_down);
            }

        }
        while (scan_up < scan_down);

        a[low] = a[scan_down];
        a[scan_down] = middle_key;

        if (low < scan_down - 1)
            this.sort(a, ckey, low, scan_down - 1);

        if (scan_down + 1 < hight)
            this.sort(a, ckey, scan_down+1, hight);

        return a;
    }

    return this.sort(a, ckey, low, hight)
}
