﻿function getCenteredCoords(width, height) {
    var xPos = null;
    var yPos = null;
    if (window.ActiveXObject) {
        xPos = window.event.screenX - (width / 2) + 100;
        yPos = window.event.screenY - (height / 2) - 100;
    } else {
        var parentSize = [window.outerWidth, window.outerHeight];
        var parentPos = [window.screenX, window.screenY];
        xPos = parentPos[0] + Math.max(0, Math.floor((parentSize[0] - width) / 2));
        yPos = parentPos[1] + Math.max(0, Math.floor((parentSize[1] - (height * 1.25)) / 2));
    }
    return [xPos, yPos];
}

function openWindow(url) {
    w = window.open(url, "openPopup", "width=680, height=480, location=1, status=1, resizable=yes");
    var coords = getCenteredCoords(680, 480);
    w.moveTo(coords[0], coords[1]);
}

function set_filter_mode(mode) {
    // set cookies
    var date = new Date();
    date.setTime(date.getTime() + (24 * 60 * 60 * 1000)); // a month
    $.cookie('gm_filter_mode', mode, { expires: date, path: '/' });

    window.location.href = "/";

    return false;
}

function header_menu(obj_selector) {
    obj_selector.hover(function() {
        $(this).addClass("hover");
        $('ul:first', this).css('visibility', 'visible');

    }, function() {
        $(this).removeClass("hover");
        $('ul:first', this).css('visibility', 'hidden');
    });
}

function do_search() {
    var keyword = $('#query');
    if (keyword.length > 0) {
        if (keyword.val().length > 2) {
            window.location.href = '/search.aspx?query=' + encodeURIComponent(keyword.val());
        }
        else {
            alert('Từ khóa tìm kiếm quá ngắn');
            keyword.focus();
        }
    }
}

function get_images(ids_list) {
    var path = '/images/upload/';
    $.ajax({
        url: '/services/getimages.ashx',
        beforeSend: function(xhr) {
            xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
        },
        data: { ids: ids_list },
        dataType: 'json',
        type: 'post',
        async: true,
        success: function(results) {
            if (results.data != null) {
                for (var i = 0; i < results.data.length; i++) {
                    var image_id = '#img-' + results.data[i].id;
                    $(image_id).attr('src', path + results.data[i].path);
                }
            }
        },
        error: function(xhr) {
            alert(xhr);
        }
    });
}

/* comment  { */
Giamua.Answer = function(options) {
    var _default = {
        min_len: 1, max_len: 4000
    };

    var _options = $.extend({}, options, _default);

    var _bindEvents = function() {
        _options.area = $('#answer-add-area');
        if (_options.area.length > 0) {
            _options.txt = _options.area.find('#txt-answer-content');
            _options.txt.autoResize({ extraSpace: 0, limit: 300 });

            _options.area.find('#btn-answer-add').click(function(e) {
                _btn_add_click();
                e.preventDefault();
            });
        }
    };

    var _btn_add_click = function() {
        if (_validation()) {
            var data = { action: 'add_answer_list', topicID: topicID, content: _options.txt.val() };
            _requestData(data);
        }
    };

    var _validation = function() {
        if (!isLoggedIn) {
            alert('Vui lòng đăng nhập để gởi bàn luận');
            return false;
        }

        txt = _options.txt;
        if (txt.val() == '' || txt.val().length < _options.min_len) {
            alert('Nội dung bàn luận quá ngắn');

            txt.focus();

            return false;
        }
        else if (txt.val().length > _options.max_len) {

        }

        return true;
    };

    var _requestData = function(requestData) {
        $.ajax({
            url: '/services/coupon/actions.ashx',
            data: requestData,
            dataType: 'json',
            type: 'post',
            async: true,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
            },
            success: function(results) {
                if (results.success == 'ok') {
                    if (requestData.action == 'add_answer_list') {
                        $('#answers-list').append(results.message);
                        $('#txt-answer-content').val('');
                    }
                    else {
                        var url = '/places/' + topicID + '/?goto=last';
                        window.location.href = url;
                    }
                }
                else {
                    alert(results.message);
                }
            },
            error: function(xhr) {
                if (xhr.status == 403) {
                    alert('Vui lòng đăng nhập để sử dụng chức năng này!');
                } else if (xhr.status == 400) {
                    alert('Yêu cầu không hợp lệ!');
                }
                else {
                    alert('Xảy ra lỗi khi thực thi!');
                }
            }
        });
    };

    return {
        init: function() {
            _bindEvents();
        }
    }
};

function reply_validation(txt) {
    if (!isLoggedIn) {
        alert('Vui lòng đăng nhập để gởi bàn luận');
        return false;
    }

    if (txt.val() == '' || txt.val().length < 1) {
        alert('Nội dung bàn luận quá ngắn');

        txt.focus();

        return false;
    }
    else if (txt.val().length > 2000) {
        alert('Nội dung bàn luận quá ngắn');

        txt.focus();

        return false;
    }

    return true;
}

var btn_reply_click = function(txt, content, answerID) {
    if (reply_validation(txt)) {
        var data = { action: 'add_reply_list', topicID: topicID, answerID: answerID, content: content };
        _replyRequestData(data, txt);
    }
};

function answer_delete(id, item) {
    if (confirm('Bạn có chắc muốn xóa bàn luận này?')) {
        var requestData = { action: 'delete_comment', id: id };
        $.ajax({
            url: '/services/coupon/actions.ashx',
            data: requestData,
            dataType: 'json',
            type: 'post',
            async: true,
            beforeSend: function(xhr) {
                xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
            },
            success: function(res) {
                if (res.success) {
                    var remove_area = $(item).closest('#answers-list .comment-item');
                    if (remove_area.length == 0)
                        remove_area = $(item).closest('#answers-list .answer-item-area');

                    remove_area.remove();
                }
                else {
                    alert(res.message);
                }
            },
            error: function(xhr) {
                if (xhr.status == 403) {
                    alert('Vui lòng đăng nhập để sử dụng chức năng này!');
                } else if (xhr.status == 400) {
                    alert('Yêu cầu không hợp lệ!');
                }
                else {
                    alert('Xảy ra lỗi khi thực thi!');
                }
            }
        });
    }
    return false;
}

var _replyRequestData = function(requestData, txt) {
    $.ajax({
        url: '/services/coupon/actions.ashx',
        data: requestData,
        dataType: 'json',
        type: 'post',
        async: true,
        beforeSend: function(xhr) {
            xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
        },
        success: function(results) {
            if (results.success == 'ok') {
                txt.closest('div.comment-box').before(results.message);
                txt.val('').focus();
            }
            else {
                alert(results.message);
            }
        },
        error: function(xhr) {
            if (xhr.status == 403) {
                alert('Vui lòng đăng nhập để sử dụng chức năng này!');
            } else if (xhr.status == 400) {
                alert('Yêu cầu không hợp lệ!');
            }
            else {
                alert('Xảy ra lỗi khi thực thi!');
            }
        }
    });
};

function show_login() {
    loginDialog.show();

    $('#simple_dialog .close').click(function(e) {
        loginDialog.close();
        e.preventDefault();
    });
}

function displayUploadForm(editor) {
    $('#div-upload').toggle();
}

var isLoggedIn = isLoggedin;
/* } comment */

var _answer;

jQuery(document).ready(function() {
    setTime();

    header_menu($('#add-menu'));

    var default_text = 'Tìm voucher';
    $('#query').focus(function() {
        if ($(this).val() == default_text) {
            $(this).val('');
        }
    }).blur(function() {
        if ($(this).val() == '') {
            $(this).val(default_text);
        }
    }).val(default_text);

    $('#query').keypress(function(e) {
        var code = (e.keyCode ? e.keyCode : e.which);
        if (code == 13) {
            do_search();
            e.preventDefault();
        }
    });

    $('#search_btn').click(function(e) {
        do_search();
        e.preventDefault();
    });

    $('#show_search_form').click(function(e) {
        $('#gm_search').toggle();
        $('#query').focus();
        e.preventDefault();
    });

    loginDialog = new Giamua.LoginDialog();

    mailDialog = new Giamua.RegisterMailDialog();
    $('#btnShowMailForm').click(function() {
        mailDialog.show();

        $('#simple_dialog .close').click(function(e) {
            mailDialog.close();
            e.preventDefault();
        });
    });

    $('#txtComment').markItUp(mySettings);
    $('#txtComment').autoResize({ limit: 300, extraSpace: 0 });

    $('div.user-action-delete').click(function() {
        jConfirm('Bạn muốn xóa tin giảm giá này?', 'Xác nhận', function(r) {
            if (r) {
                $.ajax({
                    url: '/services/deletecoupon.ashx',
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
                    },
                    data: 'id=' + current_id,
                    dataType: 'html',
                    type: 'post',
                    async: true,
                    success: function(results) {
                        jAlert('Tin giảm giá đã được xóa thành công', 'Thông báo', function() {
                            window.location.href = '/';
                        });
                    },
                    error: function(xhr) {
                        jAlert('Xảy ra lỗi khi thực thi!');
                    }
                });
            }
        })
    });

    $('span.user-delete-comment').click(function() {
        var obj = this;
        jConfirm('Bạn muốn xóa bàn luận này?', 'Xác nhận', function(r) {
            if (r) {
                $.ajax({
                    url: '/services/deletecomment.ashx',
                    beforeSend: function(xhr) {
                        xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
                    },
                    data: 'id=' + $(obj).attr('id'),
                    dataType: 'html',
                    type: 'post',
                    async: true,
                    success: function(results) {
                        window.location.href = '/deal/' + current_id;
                    },
                    error: function(xhr) {
                        jAlert('Bạn không đủ quyền để thực hiện yêu cầu này!');
                    }
                });
            }
        })
    });

    $('div.user-action-up').click(function() {
        $.ajax({
            url: '/services/upcoupon.ashx',
            beforeSend: function(xhr) {
                xhr.setRequestHeader("gm-ajax-request", 'gm-ajax-request');
            },
            data: 'id=' + current_id,
            dataType: 'html',
            type: 'post',
            async: true,
            success: function(results) {
                jAlert('Bạn đã up thành công tin giảm giá này!', 'Thông báo', function() { window.location = window.location; });
            },
            error: function(xhr) {
                jAlert('Xảy ra lỗi khi thực thi!');
            }
        });
    });

    /* comment {*/
    
    var txt = $('#txt-answer-content');
    if (txt.length > 0)
        txt.markItUp(mySettings);

    _answer = new Giamua.Answer();
    _answer.init();

    $('#link-login').click(function(e) {
        show_login();
        e.preventDefault();
    });

    $('a.link-comment').live('click', function(e) {
        if (isLoggedIn) {
            var container = $(this).closest('div.answer-item-inner');
            container.find('div.comments-list').show();
            container.find('div.comment-box').find('textarea').focus();
        }
        else {
            show_login();
        }
        e.preventDefault();
    });

    var default_text = 'Bàn luận...';
    $('#answers-list textarea').live('focusin blur', function(e) {
        if (e.type == 'focusin') {
            var txt = $(this);
            if ($(this).val().trim().length == 0 || txt.val() == default_text) {
                $(this).css('width', '497px').css('height', '40px').val('').css('color', '#333')
                    .autoResize({ extraSpace: 0, limit: 200 });
                $(this).closest('.comment-box').find('.avatar-box').show();
                $(this).closest('.comment-box').find('.btn-save').show();
            }
        }
        else {
            if ($(this).val().trim().length == 0) {
                $(this).css('width', '551px').css('height', '20px').css('color', '#888').val(default_text);
                $(this).closest('.comment-box').find('.avatar-box').hide();
                $(this).closest('.comment-box').find('.btn-save').hide();
            }
        }
    }).val(default_text).css('color', '#888'); ;

    $('.btn-save').live('click', function(e) {
        var btn = $(this);
        var box = btn.closest('div.comment-box');
        var txt = btn.prev('textarea');
        var answerID = txt.attr('id');

        btn_reply_click(txt, txt.val(), answerID);
        txt.css('height', '40px');
        e.preventDefault();
    });
    /* } comment */
});
