/*
 * Возвращает объект с абсолютной позицией элемента (.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};
}

/*
 * Выставляет значение ближайшего input:text по тексту (innerHtml) объекта
 */
function setThisValue(el)
{
    var $el = $(el);
    var $input;
    $el.parents().each(function(){
        if (!$input || $input.length!=1) {
            $input = $(this).find('input:text:first');
        }
    });
    if ($input) $input.val($el.html());
}

function gotoLink($parent)
{
    var href = $parent.find('a')[0].href;
    if (href) document.location = href;
}

var printCounter = 0;
function print_r(el, counter)
{
    if (printCounter >= counter) return false;
    printCounter++;
    var str = '';
    for (var i in el) str += i + ': '+el[i]+'; \n';
    //$('body').append('<div>'+str+'</div>');
    if (str) alert(str);
    else alert(el);
    return true;
}

function length(el) {
    var result = 0;
    for (var i in el) result++;
    return result
}

/*
 *  .setLoading() - заблокировать объект
 *  .setLoading(false) - разблокировать объект
 */
/*
var $waitBlock;
$.fn.setLoading = function (open)
{
    if (open!==false) open = true;

    var $wait = this.css('wait');
    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(this);
        this.css('wait', $wait);
    };

    if (open){
        $wait.stop().fadeIn();
    } else {
        $wait.stop().fadeOut(function(){$(this).remove();});
        this.css('wait', null);
    };
    return this;
}
*/

/*
 *  .setLoading() - заблокировать объект
 *  .setLoading(false) - разблокировать объект
 *
 *  css:
 *  div#wait {
        background-image:url('../img/wait.gif');
        background-position:center;
        background-repeat:no-repeat;
    }
 *
 *  Тени хранятся в массиве waitsAr, ключи массива - в attr объекта, к которому привязываем (this)
 */
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;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 hasPropertys(obj) {
    var result = 0;
    for (var i in obj)
        return true;
    return false;
}

function setCookie(name, value)
{
    var expDate = new Date();
    expDate.setDate(expDate.getDate() + 3600);
    document.cookie = name+'='+value+'; expires='+expDate.toUTCString();
    return true;
}

function serialize( mixed_val ) {    // Generates a storable representation of a value
    //
    // +   original by: Ates Goral (http://magnetiq.com)
    // +   adapted for IE: Ilia Kantor (http://javascript.ru)

    switch (typeof(mixed_val))
    {
        case "number":
            if (isNaN(mixed_val) || !isFinite(mixed_val)) return false;
            else return (Math.floor(mixed_val) == mixed_val ? "i" : "d") + ":" + mixed_val + ";";
        case "string":
            return "s:" + mixed_val.length + ":\"" + mixed_val + "\";";
        case "boolean":
            return "b:" + (mixed_val ? "1" : "0") + ";";
        case "object":
            var ser;
            if (mixed_val == null) return "N;";
            else if (mixed_val instanceof Array)
            {
                var idxobj = { idx: -1 };
                var map = []
                for(var i=0; i<mixed_val.length;i++)
                {
                    idxobj.idx++;
                    ser = serialize(mixed_val[i]);

                    if (ser) map.push(serialize(idxobj.idx) + ser);
                }

                return "a:" + mixed_val.length + ":{" + map.join("") + "}"
            }
            else
            {
                var class_name = get_class(mixed_val);

                if (class_name == undefined){
                    return false;
                }

                var props = new Array();
                for (var prop in mixed_val)
                {
                    ser = serialize(mixed_val[prop]);
                    if (ser) props.push(serialize(prop) + ser);
                }
                return "O:" + class_name.length + ":\"" + class_name + "\":" + props.length + ":{" + props.join("") + "}";
            }
        case "undefined":
            return "N;";
    }

    return false;
}

var $infoBlock;
function createInfoBlock()
{
    var block = '<div id="infoBlock" class="infoBlock"></div>';
    $('body').append(block);
    $infoBlock = $('#infoBlock').css({opacity:0.9});
}
function showInfo(text, time)
{
    if (!$infoBlock) createInfoBlock();
    var timeOut = $infoBlock.attr('timeOut');
    if (timeOut) {
        clearTimeout(timeOut);
        $infoBlock.attr({'timeOut': null});
    }
    $infoBlock.fadeOut('fast').html(text).fadeIn('fast');
    if (time)
    {
        timeOut = setTimeout('hideInfo()', time);
        $infoBlock.attr({'timeOut': timeOut});
    }
}
function hideInfo()
{
    var timeOut = $infoBlock.attr('timeOut');
    if (timeOut) {
        clearTimeout(timeOut);
        $infoBlock.attr({'timeOut': null});
    }
    $infoBlock.fadeOut('fast');
}

function getCaptcha(elementId, element) {
  var obj = elementId ? $("#"+elementId) : $(element);
      obj.attr("src", "/libs/Captcha/captcha.php?"+Math.random(10000));
}

