(function ($) {
    'use strict';

    function printPreview(oper) {
        var bdhtml = window.document.body.innerHTML;
        var sprnstr = '<!--startprint' + oper + '-->';
        var eprnstr = '<!--endprint' + oper + '-->';
        var prnhtml = bdhtml.substring(bdhtml.indexOf(sprnstr) + sprnstr.length);
        prnhtml = prnhtml.substring(0, prnhtml.indexOf(eprnstr));
        prnhtml = prnhtml.replaceAll('href', 'aa');
        window.document.body.innerHTML = prnhtml;
        window.print();
        window.document.body.innerHTML = bdhtml;
    }

    function updateIframe(selector, height) {
        if (parent) {
            parent.resizeIframe(selector, height);
        }
    }

    function resizeIframe(selector, height) {
        var iframe = document.getElementById(selector);
        var iHeight = iframe.contentWindow.document.body.scrollHeight || iframe.contentWindow.document.documentElement.scrollHeight;
        var iHeight2 = parseInt($(iframe).css('min-height'));
        iframe.style.height = (height ? height : (iHeight > iHeight2 ? iHeight : iHeight2)) + 'px';
    }

    function removeEmptyElement(array) {
        var result = [];
        for (var int = 0; int < array.length; int++) {
            if (array[int]) {
                result.push(array[int]);
            }
        }
        if (result.length > 0) {
            return result;
        } else {
            return null;
        }
    }

    function countDowner(count, dom, jumpHref) {
        var jumpCount = count;
        if (dom) {
            $(dom).text(jumpCount);
        }
        window.hieknjs.countDown = setInterval(function () {
            jumpCount--;
            if (jumpCount == 0) {
                clearInterval(window.hieknjs.countDown);
                if (jumpHref) {
                    window.hieknjs.goWebPage(jumpHref);
                }
            }
            if (dom) {
                $(dom).text(jumpCount);
            }
        }, 1000);
    }

    function showImgOrDefault(dom) {
        $.each($(dom), function () {
            var src = $(this).attr('src');
            var getAbsoluteLink = window.hieknjs.getAbsoluteLink;
            if (src == '' || src === null || src == 'null' || src == getAbsoluteLink('') || src == getAbsoluteLink(null) || src == getAbsoluteLink('null')) {
                $(this).attr('src', getAbsoluteLink('images/default.jpg'));
            }
        });
    }

    function placeholderBug() {
        if (!('placeholder' in document.createElement('input'))) {
            $('input[placeholder],textarea[placeholder]').each(function () {
                var that = $(this),
                    text = that.attr('placeholder');
                if (that.val() === '') {
                    that.val(text).addClass('placeholder');
                }
                that.focus(function () {
                    if (that.val() === text) {
                        that.val('').removeClass('placeholder');
                    }
                })
                    .blur(function () {
                        if (that.val() === '') {
                            that.val(text).addClass('placeholder');
                        }
                    })
                    .closest('form').submit(function () {
                    if (that.val() === text) {
                        that.val('');
                    }
                });
            });
        }
    }

    function setGoTopEvent(selector) {
        $(selector).on('click', function () {
            $('html,body').animate({scrollTop: 0}, 600);
        });
    }

    function setTableSelectEvent() {
        $('table thead input[type="checkbox"]:eq(0)').on('click', function () {
            var trs = $(this).closest('table').find('tbody').find('tr');
            for (var i = 0; i < trs.length; i++) {
                $(trs[i]).find('input[type="checkbox"]:eq(0)').prop('checked', this.checked);
            }
        });

        $('table').on('click', 'tbody input[type="checkbox"]', function () {
            if ($(this).closest('td').index() == 0) {
                var all = $(this).closest('table').find('thead').find('td:eq(0)').find('input[type="checkbox"]');
                if (this.checked) {
                    var allCheck = true;
                    var trs = $(this).closest('table').find('tbody').find('tr');
                    for (var i = 0; i < trs.length; i++) {
                        if ($(trs[i]).find('td:eq(0) input[type="checkbox"]').prop('checked') == false) {
                            allCheck = false;
                        }
                    }
                    if (allCheck) {
                        all.prop('checked', this.checked);
                    }
                } else {
                    all.prop('checked', this.checked);
                }

            }
        });
    }

    function formatPrice(price) {
        price = price + '';
        if (price.indexOf('.') > 0) {
            var sub = price.split('.')[1];
            if (sub.length == 1) {
                return price.split('.')[0] + '.' + sub + '0';
            } else if (sub.length == 2) {
                return price;
            } else {
                if (sub.charAt(2) > 4) {
                    var int = price.split('.')[0];
                    var ssub = (parseInt(sub.substring(0, 2)) + 1) + '';
                    if (ssub.length == 1) {
                        ssub = '0' + ssub;
                    } else if (ssub.length == 3) {
                        ssub = ssub.substring(1);
                        int = parseInt(int) + 1;
                    }
                    return int + '.' + ssub;
                } else {
                    return price.split('.')[0] + '.' + sub.substring(0, 2);
                }
            }
        } else if (price == '0' || price == 0) {
            return '0';
        } else {
            return price + '.00';
        }
    }

    function formatNumber(num) {
        num = num + '';
        if (num.indexOf('.') > 0) {
            var sub = num.split('.')[1];
            if (sub.length == 1) {
                return num;
            } else {
                if (sub.charAt(1) > 4) {
                    return num.split('.')[0] + 1;
                } else {
                    return num.split('.')[0] + '.' + sub.substring(0, 1);
                }
            }
        } else {
            return num;
        }
    }

    String.prototype.lTrim = function () {
        return this.replace('/(^/s*)/g', '');
    };

    String.prototype.rTrim = function () {
        return this.replace('/(/s*$)/g', '');
    };

    String.prototype.replaceAll = function (reallyDo, replaceWith, ignoreCase) {
        if (!RegExp.prototype.isPrototypeOf(reallyDo)) {
            return this.replace(new RegExp(reallyDo, (ignoreCase ? 'gi' : 'g')), replaceWith);
        } else {
            return this.replace(reallyDo, replaceWith);
        }
    };

    function lazyload(option) {
        var settings = {
            defObj: null,
            defHeight: 0
        };
        settings = $.extend(settings, option || {});
        //var defHeight = settings.defHeight, defObj = (typeof settings.defObj == 'object') ? settings.defObj.find('img') : $(settings.defObj).find('img');
        var pageTop = function () {
            return document.documentElement.clientHeight + Math.max(document.documentElement.scrollTop, document.body.scrollTop) - settings.defHeight;
        };
        var imgLoad = function () {
            settings.defObj.each(function () {
                if ($(this).offset().top <= pageTop()) {
                    var src2 = $(this).attr('src2');
                    if (src2) {
                        $(this).attr('src', src2).removeAttr('src2');
                    }
                }
            });
        };
        imgLoad();
        $(window).bind('scroll', function () {
            imgLoad();
        });
    }

    function filterNull(str) {
        if (str === null) {
            return '';
        }
        return str;
    }

    function filterZero(str) {
        if (str === null || str == '') {
            return 0;
        }
        return str;
    }

    function limitWords(text, num) {
        if (text.length >= num) {
            return text.substring(0, num) + '  ...';
        } else {
            return text;
        }
    }

    function deapMerge(a, b, arr) {
        if ($.isPlainObject(a)) {
            for (var k in a) {
                if (b[k]) {
                    deapMerge(a[k], b[k]);
                } else {
                    arr.push(b);
                }
            }
        } else if ($.isArray(a)) {
            var len = a.length;
            for (var i = 0; i < len; i++) {
                for (var j = 0; j < b.length; j++) {
                    if (($.isPlainObject(a[i]) && $.isPlainObject(b[j])) || ($.isArray(a[i]) && $.isArray(b[j]))) {
                        deapMerge(a[i], b[j], a);
                    } else {
                        a.push(b[j]);
                    }
                }
            }
        } else {
            $.merge(a, b);
        }
    }

    function pad(num, n) {
        return (Array(n).join(0) + num).slice(-n);
    }

    function goToMail(email) {
        var hash = {
            'qq.com': 'http://mail.qq.com',
            'gmail.com': 'http://mail.google.com',
            'sina.com': 'http://mail.sina.com.cn',
            '163.com': 'http://mail.163.com',
            '126.com': 'http://mail.126.com',
            'yeah.net': 'http://www.yeah.net/',
            'sohu.com': 'http://mail.sohu.com/',
            'tom.com': 'http://mail.tom.com/',
            'sogou.com': 'http://mail.sogou.com/',
            '139.com': 'http://mail.10086.cn/',
            'hotmail.com': 'http://www.hotmail.com',
            'live.com': 'http://login.live.com/',
            'live.cn': 'http://login.live.cn/',
            'live.com.cn': 'http://login.live.com.cn',
            '189.com': 'http://webmail16.189.cn/webmail/',
            'yahoo.com.cn': 'http://mail.cn.yahoo.com/',
            'yahoo.cn': 'http://mail.cn.yahoo.com/',
            'eyou.com': 'http://www.eyou.com/',
            '21cn.com': 'http://mail.21cn.com/',
            '188.com': 'http://www.188.com/',
            'foxmail.com': 'http://www.foxmail.com',
            'outlook.com': 'http://www.outlook.com'
        };

        var _mail = email.split('@')[1];
        var mail = null;
        for (var j in hash) {
            if (j == _mail) {
                mail = hash[_mail];
                break;
            }
        }
        return mail;
    }

    function log(data) {
        window.console.log(data);
    }

    function isSameIngoreObject(obj1, obj2) {
        if (obj1 instanceof Array) {
            if (obj1.length == obj2.length) {
                for (var j in obj1) {
                    if (!isSameIngoreObject(obj1[j], obj2[j])) {
                        return false;
                    }
                }
            } else {
                return false
            }
        } else if (obj1 instanceof Object) {
            for (var i in obj1) {
                if (!isSameIngoreObject(obj1[i], obj2[i])) {
                    return false;
                }
            }
        } else {
            if (obj1 !== obj2) {
                return false
            }
        }
        return true;
    }

    function isWeiXin() {
        var ua = window.navigator.userAgent.toLowerCase();
        return ua.match(/MicroMessenger/i) == 'micromessenger';
    }

    function addLocaleCompare() {
        String.prototype.localeCompare = function (target) {
            var source = this.valueOf();
            if (source === target) {
                return 0;
            } else if (source > target) {
                return 1;
            } else {
                return -1;
            }
        };
    }

    window.hieknjs = window.hieknjs || {};
    window.hieknjs.printPreview = printPreview;
    window.hieknjs.updateIframe = updateIframe;
    window.hieknjs.resizeIframe = resizeIframe;
    window.hieknjs.removeEmptyElement = removeEmptyElement;
    window.hieknjs.countDowner = countDowner;
    window.hieknjs.showImgOrDefault = showImgOrDefault;
    window.hieknjs.placeholderBug = placeholderBug;
    window.hieknjs.formatPrice = formatPrice;
    window.hieknjs.formatNumber = formatNumber;
    window.hieknjs.lazyload = lazyload;
    window.hieknjs.filterNull = filterNull;
    window.hieknjs.filterZero = filterZero;
    window.hieknjs.limitWords = limitWords;
    window.hieknjs.deapMerge = deapMerge;
    window.hieknjs.pad = pad;
    window.hieknjs.goToMail = goToMail;
    window.hieknjs.setTableSelectEvent = setTableSelectEvent;
    window.hieknjs.setGoTopEvent = setGoTopEvent;
    window.hieknjs.log = log;
    window.hieknjs.isWeixin = isWeiXin;
    window.hieknjs.addLocaleCompare = addLocaleCompare;
    window.hieknjs.isSameIngoreObject = isSameIngoreObject;
})(jQuery);