﻿var yb = yb || {}
//$.ajaxSetup({ cache: false });
yb.cookie = yb.cookie || {};
yb.array = yb.array || {};
yb.cookie.get = function (key) {
    var value = yb.cookie.getRaw(key);
    if ('string' == typeof value) {
        value = decodeURIComponent(value);
        return value;
    }
    return null;
};
yb.cookie.set = function (key, value, options) {
    yb.cookie.setRaw(key, encodeURIComponent(value), options);
};
yb.cookie.remove = function (key, options) {
    options = options || {};
    options.expires = new Date(0);
    yb.cookie.setRaw(key, '', options);
};
yb.cookie.setRaw = function (key, value, options) {
    if (!yb.cookie._isValidKey(key)) {
        return;
    }

    options = options || {};
    //options.path = options.path || "/"; // meizz 20100402 设定一个初始值，方便后续的操作
    //berg 20100409 去掉，因为用户希望默认的path是当前路径，这样和浏览器对cookie的定义也是一致的

    // 计算cookie过期时间
    var expires = options.expires;
    if ('number' == typeof options.expires) {
        expires = new Date();
        expires.setTime(expires.getTime() + options.expires);
    }

    document.cookie =
        key + "=" + value
        + (options.path ? "; path=" + options.path : "")
        + (expires ? "; expires=" + expires.toGMTString() : "")
        + (options.domain ? "; domain=" + options.domain : "")
        + (options.secure ? "; secure" : '');
};

yb.cookie._isValidKey = function (key) {
    return (new RegExp("^[^\\x00-\\x20\\x7f\\(\\)<>@,;:\\\\\\\"\\[\\]\\?=\\{\\}\\/\\u0080-\\uffff]+\x24")).test(key);
};
yb.cookie.getRaw = function (key) {
    if (yb.cookie._isValidKey(key)) {
        var reg = new RegExp("(^| )" + key + "=([^;]*)(;|\x24)"),
            result = reg.exec(document.cookie);

        if (result) {
            return result[2] || null;
        }
    }
    return null;
};
yb.array.remove = function (source, condition) {
    var len = source.length,
        iterator = condition;

    if ('function' != typeof condition) {
        iterator = function (item) {
            return condition === item;
        };
    }

    while (len--) {
        if (true === iterator.call(source, source[len], len)) {
            source.splice(len, 1);
        }
    }
    return source;
};

yb.array.removeAt = function (source, index) {
    return source.splice(index, 1)[0];
};
yb.array.indexOf = function (source, condition, position) {
    var len = source.length,
        iterator = condition;
    position = Number(position) || 0;
    position = position < 0 ? Math.ceil(position) : Math.floor(position); 
    position = Math.min(Math.max(position, 0), len);
    
    if ('function' != typeof condition) {
        iterator = function (item) {
            return condition === item;
        };
    }
    
    for ( ; position < len; position++) {
        if (true === iterator.call(source, source[position], position)) {
            return position;
        }
    }
    
    return -1;
};
//yb.init = function (obj) {
//    obj = eval(obj);
//    $("#tmpl001_c").html(obj.homeTop);
//    $("#home_entity_c").html(obj.sysClass);
//    new yb.home_loop();
//    yb.home_entity.run();
//}


yb.linkFakeSelectors = function (config) {
    this.config = {
        root: "main-wrap",
        targetClass: "link-fake-selector",
        listContainerClass: "list-container",
        selectorMoverClass: "selector-mover",
        maskEnableClass: "mask-enable",
        optionOpenClass: "option-open"
    };
    this.init();
    return this;
}
$.extend(yb.linkFakeSelectors.prototype, {
    init: function (customConfig) {
        this.config = $.extend({}, this.config, customConfig);
        var isSelectorsClick = false;
        var _self = this; var config = this.config;
        var refineByBox = $(config.root);
        var linkFakeSelectors = $('.' + config.targetClass);
        var linkFakeSelectorsLists = $('.' + config.listContainerClass);
        var selectorOnMouseover = function () {
            if (this.keyListenerInput) {
                $(this.keyListenerInput.lastSelect).removeClass('current');
                this.keyListenerInput.lastKeyIndex = "";
                this.keyListenerInput.keyIndexTimes = 0;
            }
        }
        var selectorOnClick = function (e) {
            isSelectorsClick = true;
            var curList = $('.' + config.listContainerClass, this)[0];
            for (var i = 0; i < linkFakeSelectorsLists.length; i++) {
                list = linkFakeSelectorsLists[i];
                if (list !== curList) {
                    $(list).removeClass(config.optionOpenClass);
                }
            }
            _self.transDisplay(curList, config.optionOpenClass);
        }
        linkFakeSelectors.mouseover(selectorOnMouseover);
        linkFakeSelectors.click(selectorOnClick);
        $(document).click(function (e) {
            if (!isSelectorsClick) {
                linkFakeSelectorsLists.removeClass(config.optionOpenClass);
            }
            isSelectorsClick = false;
        })
        if ($.browser.msie) {
            CollectGarbage();
        }

    },
    transDisplay: function (el, flagClass) {
        var result;
        if (!$.isArray(el)) { el = [el]; }
        for (var i = 0, j = el.length; i < j; i++) {
            var elItem = el[i];
            if ($(elItem).hasClass(flagClass)) {
                $(elItem).removeClass(flagClass);
                result = false;
            } else {
                $(elItem).addClass(flagClass);
                result = true;
            }
        }
        return result;
    }
});
yb.dialog_count=1;
yb.dialog_zindex = 999999;
yb.dialog = function (content, options) {
    var defaults = { // 默认值。 
        title: '',       // 标题文本，若不想显示title请通过CSS设置其display为none 
        showTitle: true,     // 是否显示标题栏。
        closeText: '[Закрыть]', // 关闭按钮文字，若不想显示关闭按钮请通过CSS设置其display为none 
        draggable: true,     // 是否移动 
        modal: true,         // 是否是模态对话框 
        center: true,        // 是否居中。 
        fixed: true,         // 是否跟随页面滚动。
        time: 0,             // 自动关闭时间，为0表示不会自动关闭。 
        id: false            // 对话框的id，若为false，则由系统自动产生一个唯一id。 
    };
    var options = $.extend(defaults, options);
    options.id = options.id ? options.id : 'dialog-' + yb.dialog_count; // 唯一ID
    var overlayId = options.id + '-overlay'; // 遮罩层ID
    var timeId = null;  // 自动关闭计时器 
    var isShow = false;
    var isIe = $.browser.msie;
    var isIe6 = $.browser.msie && ('6.0' == $.browser.version);
    //    yb.dialog.__zindex = 9999;
    //    yb.dialog.__count = 1;
    yb.dialog.version = '1.0 beta';
    /* 对话框的布局及标题内容。*/
    var barHtml = !options.showTitle ? '' :
        '<div class="bar"><span class="title">' + options.title + '</span><a class="close">' + options.closeText + '</a></div>';
    var dialog = $('<div id="' + options.id + '" class="dialog">' + barHtml + '<div class="content"></div></div>').hide();
    $('body').append(dialog);


    /**
    * 重置对话框的位置。
    *
    * 主要是在需要居中的时候，每次加载完内容，都要重新定位
    *
    * @return void
    */
    var resetPos = function () {
        /* 是否需要居中定位，必需在已经知道了dialog元素大小的情况下，才能正确居中，也就是要先设置dialog的内容。 */
        if (options.center) {
            var left = ($(window).width() - dialog.width()) / 2;
            var top = ($(window).height() - dialog.height()) / 2;
            if (!isIe6 && options.fixed)
            { dialog.css({ top: top, left: left }); }
            else
            { dialog.css({ top: top + $(document).scrollTop(), left: left + $(document).scrollLeft() }); }
        }
    }

    /**
    * 初始化位置及一些事件函数。
    *
    * 其中的this表示Dialog对象而不是init函数。
    */
    var init = function () {
        /* 是否需要初始化背景遮罩层 */
        if (options.modal) {
            $('body').append('<div id="' + overlayId + '" class="dialog-overlay"></div>');
            $('#' + overlayId).css({ 'left': 0, 'top': 0,
                /*'width':$(document).width(),*/
                'width': '100%',
                /*'height':'100%',*/
                'height': $(document).height(),
                'z-index': ++yb.dialog_zindex,
                'position': 'absolute'
            }).hide();
        }

        dialog.css({ 'z-index': ++yb.dialog_zindex, 'position': options.fixed ? 'fixed' : 'absolute' });

        /*  IE6 兼容fixed代码 */
        if (isIe6 && options.fixed) {
            dialog.css('position', 'absolute');
            resetPos();
            var top = parseInt(dialog.css('top')) - $(document).scrollTop();
            var left = parseInt(dialog.css('left')) - $(document).scrollLeft();
            $(window).scroll(function () {
                dialog.css({ 'top': $(document).scrollTop() + top, 'left': $(document).scrollLeft() + left });
            });
        }

        /* 以下代码处理框体是否可以移动 */
        var mouse = { x: 0, y: 0 };
        function moveDialog(event) {
            var e = window.event || event;
            var top = parseInt(dialog.css('top')) + (e.clientY - mouse.y);
            var left = parseInt(dialog.css('left')) + (e.clientX - mouse.x);
            dialog.css({ top: top, left: left });
            mouse.x = e.clientX;
            mouse.y = e.clientY;
        };
        dialog.find('.bar').mousedown(function (event) {
            if (!options.draggable) { return; }

            var e = window.event || event;
            mouse.x = e.clientX;
            mouse.y = e.clientY;
            $(document).bind('mousemove', moveDialog);
        });
        $(document).mouseup(function (event) {
            $(document).unbind('mousemove', moveDialog);
        });

        /* 绑定一些相关事件。 */
        dialog.find('.close').bind('click', this.close);
        dialog.bind('mousedown', function () { dialog.css('z-index', ++yb.dialog_zindex); });

        // 自动关闭 
        if (0 != options.time) { timeId = setTimeout(this.close, options.time); }
    }


    /**
    * 设置对话框的内容。 
    *
    * @param string c 可以是HTML文本。
    * @return void
    */
    this.setContent = function (c) {
        var div = dialog.find('.content');

        if ('object' == typeof (c)) {
            switch (c.type.toLowerCase()) {
                case 'id': // 将ID的内容复制过来，原来的还在。
                    var clone = $('#' + c.value).clone(true);
                    clone.show();
                    div.empty();
                    div.append(clone);
                    break;
                case 'img':
                    div.html('Загрузка...');
                    $('<img alt="" />').load(function () { div.empty().append($(this)); resetPos(); })
                    .attr('src', c.value);
                    break;
                case 'url':
                    div.html('Загрузка...');
                    $.ajax({ url: c.value,
                        success: function (html) { div.html(html); resetPos(); },
                        error: function (xml, textStatus, error) { div.html('出错啦') }
                    });
                    break;
                case 'iframe':
                    div.append($('<iframe src="' + c.value + '" />'));
                    break;
                case 'text':
                default:
                    div.html(c.value);
                    break;
            }
        }
        else
        { div.html(c); }
        div.mouseover(function () {
            resetPos();
        })
        div.click(function () {
            resetPos();
        })
    }

    /**
    * 显示对话框
    */
    this.show = function () {
        if (undefined != options.beforeShow && !options.beforeShow())
        { return; }

        /**
        * 获得某一元素的透明度。IE从滤境中获得。
        *
        * @return float
        */
        var getOpacity = function (id) {
            if (!isIe)
            { return $('#' + id).css('opacity'); }

            var el = document.getElementById(id);
            return (undefined != el
                    && undefined != el.filters
                    && undefined != el.filters.alpha
                    && undefined != el.filters.alpha.opacity)
                ? el.filters.alpha.opacity / 100 : 1;
        }

        /* 是否显示背景遮罩层 */
        if (options.modal) {
            //$('#' + overlayId).fadeTo('fast', 0.2);

        }
//        dialog.fadeTo('fast', 1, function () {
//            if (undefined != options.afterShow) {
//                options.afterShow();
//            }
//            isShow = true;
//        });
        dialog.show(0, function () {
            if (undefined != options.afterShow) {
                options.afterShow();
            }
            isShow = true;
        });

        // 自动关闭 
        if (0 != options.time) { timeId = setTimeout(this.close, options.time); }
        resetPos();
        return $(dialog);
    }


    /**
    * 隐藏对话框。但并不取消窗口内容。
    */
    this.hide = function () {
        if (!isShow) { return; }

        if (undefined != options.beforeHide && !options.beforeHide())
        { return; }

//        dialog.fadeOut('fast', function () {
//            if (undefined != options.afterHide) { options.afterHide(); }
//        });
        dialog.show(0, function () {
            if (undefined != options.afterHide) { options.afterHide(); }
        });
        if (options.modal)
        { $('#' + overlayId).fadeOut('fast'); }

        isShow = false;
    }

    /**
    * 关闭对话框 
    *
    * @return void
    */
    this.close = function () {
        if (undefined != options.beforeClose && !options.beforeClose())
        { return; }

//        dialog.fadeOut('fast', function () {
//            $(this).remove();
//            isShow = false;
//            if (undefined != options.afterClose) { options.afterClose(); }
//        });
        dialog.hide(0, function () {
            $(this).remove();
            isShow = false;
            if (undefined != options.afterClose) { options.afterClose(); }
        });
        if (options.modal)
        { $('#' + overlayId).fadeOut('fast', function () { $(this).remove(); }); }
        clearTimeout(timeId);
    }
    init.call(this);
    this.setContent(content);
    return this;

}
yb.keyword = function () {
    $.get("/json/Keywords", function (data) {
        var el = $("#keywords");
        el.html(data);
        el.show();
    });
}
yb.news = function () {
    this.init();
}
$.extend(yb.news.prototype, {
    current: 0,
    count: 0,
    jsonData: null,
    stop: false,
    interval: null,
    init: function () {
        var _this = this;
        document.write('<div class="footerNews" ></div>');
        $.get("/json/news", null, function (data) {
            _this.jsonData = data;
            _this.formatHTML();
        });
    },
    formatHTML: function () {
        var _this = this;
        var data = _this.jsonData;
        if (data == undefined || data.length < 0) {
            return;
        }
        var el = $(".footerNews");
        
        var html = "<ul>";
        for (var i = 0; i < data.length; i++) {
            var item = data[i];
            html += "<li><span>Новости yabao365 </span><a href=\"" + item.url + "\">" + item.title + "</a></li>";
        }
        html += "</ul>";
        el.append(html);
        _this.count = data.length;
        _this.bind();
    },
    bind: function () {
        var _this = this;
        var el = $(".footerNews");
        var el_ul = $("ul", el);
        el.hover(function () { _this.stop = true; }, function () { _this.stop = false; })
        _this.interval = setInterval(function () {
            if (_this.stop)
                return;
            el_ul.animate({
                marginTop: "-" + _this.current * 25 + "px"
            });
            if ((_this.current + 1) < _this.count) {
                _this.current++;
            }
            else {
                _this.current = 0;
            }
        }, 1800);
    }
});
yb.welcome = function () {
    this.init();
}
$.extend(yb.welcome.prototype, {
    dialog: null,
    init: function () {
        this.load_data();

    },
    load_data: function () {
        var _this = this;
        var c_info = $("#welcome_info");

        $.ajaxSetup({ cache: false });
        $.get("/json/WelcomeInfo", function (data) {
            c_info.html('<span id="msn_c" style="cursor: pointer;"><img style="border-style: none;" src="http://messenger.services.live.com/users/a8cbefe595218d1f@apps.messenger.live.com/presenceimage?mkt=ru-ru" width="16" height="16" />обслуживание клиентов он лайн | </span>' + data.data1);
            var html_login = data.data2;
            var c_info_login = $(".login", c_info);
            //var c_info_reg = $("#register", c_info);
            c_info_login.click(function () {
                _this.dialog = new yb.dialog(html_login, { draggable: false }).show();
                _this.bind_login();
            }); 
            $("#msn_c").click(function () {
                var msnPopup = window.open("http://settings.messenger.live.com/Conversation/IMMe.aspx?invitee=a8cbefe595218d1f@apps.messenger.live.com&mkt=ru-ru", "", "top=100,left=200;location=no,status=no,toolbar=no,menubar=no,width=300,height=400")
                msnPopup.opener.focus();
            });
//            c_info_reg.click(function () {
//                //new yb.dialog().show();
//            })
        })
    },
    bind_login: function () {
        var c_login = $("#c_login");
        var _this = this;
        $("input[type=submit]", c_login).click(function () {
            var loginEmail = $("input[name=loginEmail]", c_login).val();
            var pwd = $("input[name=pwd]", c_login).val();
            $.ajaxSetup({ cache: false });
            $.get("/json/Post_login", { loginEmail: loginEmail, pwd: pwd }, function (data) {
                if (data.check) {
                    window.location.reload();
                }
                else {
                    new yb.dialog('<div style="padding:20px;font-size:14px;background:#fff;">Имя пользователя и пароль не совпадают</div>', { modal: false, time: 3000 }).show();
                }
            });
        })
    }
});

yb.welcomeuser = function () {
    this.init();
}
$.extend(yb.welcomeuser.prototype, {
    dialog: null,
    init: function () {
        this.load_data();
    },
    load_data: function () {
        var _this = this;
        var c_info = $("#welcomeuser_info");

        $.ajaxSetup({ cache: false });
        $.get("/json/WelcomeUserInfo", function (data) {
            c_info.html(data.data1)
            var html_login = data.data2;
            var c_info_login = $(".login", c_info);
            //var c_info_reg = $("#register", c_info);
            c_info_login.click(function () {
                _this.dialog = new yb.dialog(html_login, { draggable: false }).show();
                _this.bind_login();
            });
        })
    },
    bind_login: function () {
        var c_login = $("#c_login");
        var _this = this;
        $("input[type=submit]", c_login).click(function () {
            var loginEmail = $("input[name=loginEmail]", c_login).val();
            var pwd = $("input[name=pwd]", c_login).val();
            $.ajaxSetup({ cache: false });
            $.get("/json/Post_login", { loginEmail: loginEmail, pwd: pwd }, function (data) {
                if (data.check) {
                    window.location.reload();
                }
                else {
                    new yb.dialog('<div style="padding:20px;font-size:14px;background:#fff;">Имя пользователя и пароль не совпадают</div>', { modal: false, time: 3000 }).show();
                }
            });
        })
    }
});



$(function () {
    //模拟Selecter
    $(".search-select-box").click(function () {
        var s = $(".search-category-list").css("display");
        if (s == "none") {
            $(".search-category-list").css({ "display": "" });
        }
        else {
            $(".search-category-list").css({ "display": "none" });
        }
    });

    //分类选择鼠标覆盖样式
    $(".search-category-list li").hover(function () {
        $(this).addClass("hover");
    }, function () {
        $(this).removeClass("hover");
    })


    //选择分类选项
    $(".search-category-list li").each(function () {
        $(this).click(function () {
            var value = $(this).attr("title");

            var text = $(this).text();
            $(".sysClassText").val(text);
            $("#sysClass").val(value);
        })
    })

    $(".search-category-list").mouseleave(function () {
        $(this).css({ "display": "none" });
    })
})
