/**
 * @author Denis Barushev <barushev@gmail.com>
 * @since 08.10.2008
 */

String.prototype.printAddr =
    function (_hamper,_prefix,_postfix,_face) {
        _hamper= _prefix+
                "@"+
                this+
                (_postfix || '');
        document.write((_face||_hamper).link("mailto:"+_hamper));
    };

function showPopupAd(entid) {
    var top = parseInt(($("html")[0].clientHeight - 545)/2);

    if (top < 0) {
        top = 10;
    }

    $('#request_ad')
        .find('.ad_info')
            .find('.price').html(ads[entid].price).end()
            .find('h3 a').html(ads[entid].title).attr('href', ads[entid].url).end()
            .find('.photo img').attr('src', ads[entid].photo).end()
            .find('.contacts').html(ads[entid].contacts).end()
            .find('.description').html(ads[entid].body).end()
            .find('input').val(entid).end()
        .end()
        .hide().css("top", document.lastChild.scrollTop + top + 7).show();
}

function ajaxFinish() {
    document.body.style.cursor = 'default';
    $('#request_ad form input[type=submit]').attr('disabled', '');
}

function ajaxStart() {
    document.body.style.cursor = 'wait';
    $('#request_ad form input[type=submit]').attr('disabled', 'disabled');
}

function requestFormSubmit(frm) {

    var hasErrors = false;

    $('input[name=name]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=phone]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=email]', frm).each( function () {
        if ( this.value.match(/[^\s]/) && !this.value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=phone]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );


    $('input[name=captcha]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    if ( hasErrors ) {
        return false;
    }

    $.ajaxSetup(
        {
            dataType: 'json',
            error: ajaxFinish
        }
    );

    var frm_data = {
        'entid': $('input[name=entid]').val(),
        'name': $('input[name=name]').val(),
        'phone': $('input[name=phone]').val(),
        'email': $('input[name=email]').val(),
        'captcha': $('input[name=captcha]').val()
    };

    ajaxStart();
    $.post(
        '/ajax/send-request.json',
        frm_data,
        function (json) {
            ajaxFinish();
            if ( json['error'] != '' ) {
                alert(json['error']);
            }
            else {
                $('#request_ad table').hide();
                $('#request_ad table tr.captcha').remove();
                $('#ad_request_sended').show();
            }
        }
    );

    return true;
}

function clearErrors() {
    $('form div.error').hide();
    $('form tr.error').removeClass('error');
}

function addError(el) {
    $(el).parents('tr:first').addClass('error');
}

function newAdFormSubmit(frm) {

    clearErrors();
    var hasErrors = false;

    $('textarea[name=body]', frm).each( function() {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=contact]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=phone]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=email]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
        else if ( this.value.match(/[^\s]/) && !this.value.match(/^[a-z0-9_\-\.]+@([a-z0-9_\-]+\.)+[a-z]{2,5}$/i) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    $('input[name=captcha]', frm).each( function () {
        if ( this.value.match(/^\s*$/) ) {
            addError(this);
            hasErrors = true;
        }
    } );

    if ( hasErrors ) {
        $('form div.error').show();
    }

    return !hasErrors;
}

function closeRequestForm() {
    $('#request_ad').hide();
    $('#request_ad table').show();
    $('#ad_request_sended').hide();
}

$(function () {
    $('input.combobox').combobox();

    $('table.ads td.request span, .contacts span.request').click(
        function () {
            showPopupAd($(this).attr('rel'));
        }
    );

    $('#new_ad .add_file').click(
        function () {
            $('#new_ad .files li.dummy').clone(true).appendTo('#new_ad .files').removeClass('dummy');
        }
    );

    $('#new_ad .delete_file').click(
        function () {
            $(this).parent().remove();
        }
    );

    $(document).accesskey(
        'escape',
        function () {
            $('#request_ad').hide();
            $('#jquery-lightbox').remove();
            $('#jquery-overlay').fadeOut(function() { $('#jquery-overlay').remove(); });
            // Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
            $('embed, object, select').css({ 'visibility' : 'visible' });
            // Close all comboboxes
            $('div.combobox').removeClass('expanded');
        },
        true
    );

    $('.ad .photos li a').lightBox({
        imageLoading:    '/media/images/lightbox/ico-loading.gif',
        imageBtnPrev:    '/media/images/lightbox/btn-prev.gif',
        imageBtnNext:    '/media/images/lightbox/btn-next.gif',
        imageBtnClose:   '/media/images/lightbox/btn-close.gif',
        imageBlank:      '/media/images/lightbox/blank.gif',
        txtImage:        'Фото',
        txtOf:           'из'
    });

    $('dl.qa dt').click(
        function () {
            $(this).toggleClass('expanded').next().toggle();
        }
    );

    $('div.send_message a').click(
        function () {
            $.jqURL.loc(this.href, {w: 640, h: 640, wintype: '_blank'})
                return false;
        }
    );

    $('#request_ad form').submit(
        function () {
            requestFormSubmit(this);
            return false;
        }
    );

    $('#new_ad').submit(
        function () {
            return newAdFormSubmit(this);
        }
    );

    $.preload(['bgs/popup.png', 'icons/close.gif', 'bgs/shadow_bl.png', 'bgs/shadow_tr.png'], {base: '/media/images/'});
});
