/**
 * 站点通用脚本
 *
 * @author     Akon(番茄红了) <aultoale@gmail.com>
 * @copyright  Copyright (c) 2008 (http://www.imeelee.com/)
 */

/**
 * 格式化数字字符，保留小数位
 */
String.prototype.numberFormat = function(decimals){
    if (isNaN(this)) { return 0; };
    if (this == '') { return 0; };
    var sec = this.split('.');
    var whole = parseFloat(sec[0]);
    var result = '';
    if (sec.length > 1) {
        var dec = new String(sec[1]);
        dec = String(parseFloat(sec[1]) / Math.pow(10, (dec.length - decimals)));
        dec = String(whole + Math.round(parseFloat(dec)) / Math.pow(10, decimals));
        var dot = dec.indexOf('.');
        if (dot == -1) {
            dec += '.';
            dot = dec.indexOf('.');
        }
        while (dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    } else {
        var dot;
        var dec = new String(whole);
        dec += '.';
        dot = dec.indexOf('.');
        while (dec.length <= dot + decimals) { dec += '0'; }
        result = dec;
    }
    return result;
};

/**
 * 反转 PHP 的 nl2br
 */
String.prototype.br2nl = function(){
     var re = /(<br\/>|<br>|<BR>|<BR\/>)/g;
     return this.replace(re, "\n");
}

/**
 * 根据下标移除数组元素
 */
Array.prototype.remove = function(index){
    if (isNaN(index) || index > this.length) { return false; }
    for (var i = 0, n = 0; i < this.length; i++) {
        if (this[i] != this[index]) {
            this[n++] = this[i];
        }
    }
    this.length -= 1;
}

/**
 * bgiframe
 */
$.fn.bgiframe = function(s) {
    // This is only for IE6
    if ( $.browser.msie && /6.0/.test(navigator.userAgent) ) {
        s = $.extend({
            top     : 'auto', // auto == .currentStyle.borderTopWidth
            left    : 'auto', // auto == .currentStyle.borderLeftWidth
            width   : 'auto', // auto == offsetWidth
            height  : 'auto', // auto == offsetHeight
            opacity : true,
            src     : 'javascript:false;'
        }, s || {} );
        var prop = function(n){ return n&&n.constructor == Number?n + 'px' : n; },
            html = '<iframe class="bgiframe" frameborder="0" tabindex="-1" src="' + s.src + '"' +
                       'style="display:block;position:absolute;z-index:-1;' +
                           (s.opacity !== false ? 'filter:Alpha(Opacity=\'0\');' : '') +
                           'top:' + (s.top=='auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderTopWidth)||0)*-1)+\'px\')' : prop(s.top)) + ';' +
                           'left:' + (s.left=='auto' ? 'expression(((parseInt(this.parentNode.currentStyle.borderLeftWidth)||0)*-1)+\'px\')' : prop(s.left)) + ';' +
                           'width:' + (s.width=='auto' ? 'expression(this.parentNode.offsetWidth+\'px\')' : prop(s.width)) + ';' +
                           'height:' + (s.height=='auto' ? 'expression(this.parentNode.offsetHeight+\'px\')' : prop(s.height)) + ';' +
                    '"/>';
        return this.each(function() {
            if ( $('> iframe.bgiframe', this).length == 0 )
                this.insertBefore(document.createElement(html), this.firstChild );
        });
    }
    return this;
};

/**
 * 为对像绑定下拉菜单
 */
$.fn.bindDropMenu = function(target, offsetX, offsetY){
    var offset = false;
    var show = function(){
        if (!offset) {
            offsetX = isNaN(offsetX) ? 0 : parseInt(offsetX);
            offsetY = isNaN(offsetY) ? 0 : parseInt(offsetY);
            $(target).css('left', $(this).offset().left + offsetX)
                     .css('top', $(this).offset().top + $(this).height() + offsetY);
            offset = true;
        }
        $(target).show().bgiframe();
    };
    var hide = function(){$(target).hide();};
    $(this).each(function(){
        $(this).hover(show, hide);});
    $(target).hover(show, hide);
};

/**
 * TABS 效果
 */
$.fn.tabs = function(event, elements){
    event = (event == 'click') ? 'click' : 'mouseover';
    $(this).each(function(){
        var eles = [];
        if (!elements) {
            $(this).find('li').each(function(){
                eles.push($($(this).find('a').attr('href')));
            });
        }
        $(this).find('li').bind(event, function(){
            (!elements) ?
                $.each(eles, function(i){eles[i].css('height', '0px').hide()})
                : $(elements).css('height', '0px').hide();
            $($(this).find('a').attr('href')).css('height', 'auto').show();
            $(this).parent().find('li').removeClass('current');
            $(this).addClass('current');
            $(this).find('a').blur();
            return false;
        }).unbind(event == 'click' ? 'mouseover' : 'click');
    });
};

/**
 * 购物车
 */
function Cart(){

    this.url = { //网址参数
        'base'      : 'http://shop.imeelee.com',
        'file'      : 'http://www.imeelee.com',
        'goods'     : '/%d.html',
        'brand'     : '/brand/view/id/%d',
        'settle'    : '/order/checkout',
        //---- cart ----
        'cart'      : '/cart/list',
        'goodsinfo' : '/cart/ajaxGoods',
        'add'       : '/cart/ajaxAdd',
        'setqty'    : '/cart/ajaxSet',
        'remove'    : '/cart/ajaxRemove',
        'save'      : '/cart/save',
        'clear'     : '/cart/clear'
    };
    this.items = []; //商品数据数组
    this.totalQty = 0; //商品总数量
    this.totalPrice = 0; //总金额

    //直接设置购物车的商品数据
    this.setItems = function(items){
        if (typeof items == 'object') {
            this.items = []; //清空购物车
            this.totalQty = this.totalPrice = 0;
            for (var i=0; i<items.length; i++) {
                if (items[i].qty > 0) {
                    this.totalQty += items[i].qty;
                    this.totalPrice += items[i].qty * items[i].price;
                    this.items.push(items[i]);
                }
            }
        }
        this.update();
    };

    //获取商品网址
    this.getItemUrl = function(id) {
        return this.url.base + this.url.goods.replace('%d', id);
    };

    //获取品牌网址
    this.getBrandUrl = function(id){
        return this.url.base + this.url.brand.replace('%d', id);
    };

    //获取商品缩略图地址
    this.getThumb = function(image){
        var idx = image.lastIndexOf('.');
        image = image.substr(0, idx) + '.(50)' + image.substr(idx);
        return this.url.file + image.replace('/uploads/goods/', '/thumb/goods/');
    };

    //更新购物车信息(HTML)
    this.update = function(){
        var url = this.url;
        $('#cart li.c').html('<a href="' + url.base + url.cart + '" title="您的购物车中共有 ' + this.totalQty + ' 件商品">购物车有 <strong>' + this.totalQty + '</strong> 件商品 </a>');
        if (this.totalQty > 0) {
            var html = '<table width="440" border="0" cellspacing="0" cellpadding="0">';
            for (var i = 0; i < this.items.length; i++) {
                var item = this.items[i];
                html += '<tr><td width="60" height="70" align="center"><a href="' + this.getItemUrl(item.id)
                     +  '" title="' + item.name + '" class="img"><img src="' + this.getThumb(item.image) + '" /></a></td>'
                     +  '<td width="270" align="left" valign="middle"><div class="name">'
                     +  '<a href="' + this.getItemUrl(item.id) + '" title="' + item.name + '">' + item.name;
                if (item.special == 1) {
                    html += ' <font color="red">(特价)</font>';
                }
                if (item.gift == 1) {
                    html += ' <font color="red">(赠品)</font>';
                }
                if (item.ship == 1) {
                    html += ' <font color="red">(包邮)</font>';
                }
                html += '</a></div><div class="brand">品牌：<a href="' + this.getBrandUrl(item.bid) + '" title="点击进入品牌首页">'
                     +  item.bname + '</a></div></td>'
                     +  '<td width="80" align="right"><div class="price">' + item.price + ' × ' + item.qty + '</div></td>'
                     +  '<td width="30" align="center"><a href="javascript:void(0);" title="从购物车中删除这个商品" class="del" onclick="cart.removeItem('
                     +  item.id + ');"><img src="/v3/images/no.gif" alt="删除" /></a></td>'
                     +  '</tr><tr><td colspan="4" height="1" background="/v3/images/bg_dashed.gif"></td></tr>';
            }
            html += '</table><table width="440" border="0" cellspacing="0" cellpadding="0" style="margin-top:8px;">'
                 +  '<tr><td width="220" rowspan="2" align="left" valign="top"><a href="' + url.base + url.save
                 +  '" title="&quot;寄存购物车&quot;可以保存您的购物车，当您下次登录时，系统将自动装载。" class="save">寄存购物车</a></td>'
                 +  '<td width="220" align="right"><div class="info"';
            var diffPrice = 298 - this.totalPrice;
            if (diffPrice > 0) {
                html += 'title="还差 ' + diffPrice.toString().numberFormat(2) + ' 元就可满 298 元免运费哦，加油！"';
            }
            html += '>共 <strong>' + this.totalQty + '</strong> 件商品，总金额：<strong>￥' + this.totalPrice.toString().numberFormat(2) + '</strong> 元</div></td>'
                 +  '</tr><tr><td align="right"><a href="' + url.base + url.settle
                 +  '" title="前往订单结算页面"><img src="/v3/images/btn_settle.gif" alt="结算" vspace="4" hspace="2" /></a></td>'
                 +  '</tr></table>';
        } else {
            var html = '<center style="line-height:30px; color:#666; margin-top:3px;">您尚未选购任何商品，赶快去选择适合您的商品吧！</center>';
        }
        $('#cart-list').html(html);
    };

    //获取商品信息
    this.getItem = function(id){
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == id) {
                return this.items[i];
            }
        }
        return null;
    };

    //查询商品是否存在
    this.hasItem = function(id){
        var data = this.getItem(id);
        return data == null ? false : true;
    };

    //添加商品
    this.addItem = function(id, qty, callback){
        var data = this.getItem(id);
        if (data == null) {
            //获取商品信息
            $.get(this.url.base + this.url.goodsinfo, {'id' : id}, function(data){
                var result = false;
                if (data.length > 5) {
                    data.qty = qty;
                    $.get(this.url.base + this.url.add, {'id' : id, 'qty' : qty}); //添加商品
                    this.totalQty += qty;
                    this.totalPrice += qty * data.price;
                    this.items.push(data);
                    this.update();
                    result = true;
                }
                if (typeof callback == 'function') { callback(result); }
            });
        } else {
            this.setItem(id, data.qty + qty, callback); //修改数量
        }
    };

    //设置商品数量
    this.setItem = function(id, qty, callback) {
        $.get(this.url.base + this.url.setqty, {'id' : id, 'qty' : qty});
        var result = false;
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == id) {
                this.totalQty = this.totalQty - this.items[i].qty + qty;
                this.totalPrice = this.totalPrice - (this.items[i].qty * this.items[i].price) + (qty * this.items[i].price);
                this.items[i].qty = qty;
                this.update();
                result = true;
                break;
            }
        }
        if (typeof callback == 'function') { callback(result); }
        return result;
    };

    //删除商品
    this.removeItem = function(id, qty, callback) {
        $.get(this.url.base + this.url.remove, {'id' : id});
        var result = false;
        for (var i = 0; i < this.items.length; i++) {
            if (this.items[i].id == id) {
                this.totalQty -= this.items[i].qty;
                this.totalPrice -= this.items[i].qty * this.items[i].price;
                this.items.remove(i);
                this.update();
                result = true;
                break;
            }
        }
        if (typeof callback == 'function') { callback(result); }
        return result;
    };

    //清空购物车
    this.clear = function(callback){
        $.get(this.url.base + this.url.clear);
        this.items = [];
        this.totalQty = this.totalPrice = 0;
        this.update();
        if (typeof callback == 'function') { callback(true); }
    };

    //初始化
    this.init = function(){
        this.update();
        $('#cart li.c').bindDropMenu('#cart-list', -138);
    };
};

var cart = new Cart(); //初始化购物车

/**
 * 将指定元素创建为对话框
 */
$.fn.dialog = function(o){
    var p = {title : '', modal : true};
    $.extend(p, o);
    return this.each(function(){
        if ($(this).find('.jqmMain').length == 0) {
            $(this).wrapInner('<div class="jqmMain"></div>');
            if (p.title.length > 0) {
               $(this).prepend('<div class="jqmTop"><h4>' + p.title + '</h4><a href="javascript:void(0);" title="关闭" class="jqmClose"></a></div>');
            } else {
                p.modal = false;
            }
        }
        $(this).addClass('jqmWindow').jqm(p).jqDrag('.jqmTop').jqmShow();
    });
};

/**
 * 用户登录/退出处理
 */
var auth = {
    init : function(){
        auth = $.extend(auth, {logined : false, uid : 0, username : null, nickname : null, email : null,  avatar : null});
    },
    set : function(data){
        auth = $.extend(auth, data);
        auth.refreshNew();
    },
    loginSuccess : function(){},
    login : function() {
        var html = '<form method="post" action="/default/user/login">'
                 + '<input type="hidden" name="ajax" value="1" />'
                 + '<div class="message"></div>'
                 + '<table width="100%" border="0" cellspacing="0" cellpadding="0">'
                 + '<tr><td align="right">用户名/邮箱：</td>'
                 + '<td align="left"><input type="text" name="username" size="25" maxlength="60" class="text" tabindex="1" />'
                 + '<a href="http://www.imeelee.com/user/register" target="_parent">我还没有注册</a></td></tr>'
                 + '<tr><td align="right">登录密码：</td>'
                 + '<td align="left"><input type="password" name="password" size="25" maxlength="50" class="text" tabindex="2" />'
                 + '<a href="http://www.imeelee.com/user/forget" target="_parent">忘记密码了？</a></td></tr>'
                 + '<tr><td align="right">&nbsp;</td>'
                 + '<td align="left"><input name="lifetime" id="lifetime" type="checkbox" value="2592000" checked="checked" tabindex="3" />'
                 + '<label for="lifetime">保存密码(下次自动登录)</label></td></tr>'
                 + '<tr><td align="right">&nbsp;</td>'
                 + '<td align="left"><input type="submit" value="登 录" class="btn-1" tabindex="4" />'
                 + '<input type="button"value="取 消" class="btn-3 jqmClose" tabindex="5" /></td></tr>'
                 + '</table></form>';
        var dialog = $('<div id="login-dialog"></div').prependTo(document.body).html(html).dialog({title:'注册会员登录'});
        dialog.find('form').submit(function(){
            var $this = $(this);
            $this.find('.message').addClass('loading').html('登录请求处理中...').show();
            $this.ajaxSubmit({
                dataType : 'json',
                success : function(json){
                    $this.find('.loading').hide();
                    if (json.logined) { //登录成功
                        dialog.jqmHide();
                        auth.set(json);
                        $('#auth .center').prevAll('li').remove();
                        $('#welcome').html(
                            '<li class="nick"><img src="' + json.avatar + '" width="16" height="16" align="absmiddle" />' +
                            ' 欢迎回来，<a href="http://www.imeelee.com/user/profile" title="修改个人资料">' + json.nickname + '</a></li><li class="sep"></li>' +
                            '<li class="msg"><a href="http://www.imeelee.com/msg/list" title="0 条新消息">短消息</a></li>'
                        );
                        $('#topbar .msg').bindDropMenu('#topbar ul.msg-menu', -10, -5);
                        if (json.admin) {
                            $('#auth .service').after('<li class="sep"></li><li class="admin"><a href="http://admin.imeelee.com/" title="进入管理后台">管理后台</a></li>');
                        }
                        $('#auth .help').after('<li class="sep"></li><li class="logout"><a href="http://www.imeelee.com/user/logout" title="退出登录" onclick="return auth.logout();">退出</a></li>');
                        auth.loginSuccess();
                    } else {
                        $this.find('.message').removeClass('loading').html(json.message).show();
                        $this.find('input[name=username]').focus();
                    }
                }
            });
            return false;
        });
        return false;
    },
    logoutSuccess : function(){},
    logout : function(){ //退出登录
        $.get('/default/user/logout', function(){
            auth.init();
            $('#auth .center').before(
                '<li>您好，请 <a href="http://www.imeelee.com/user/login" title="注册会员请点击登录" class="login" onclick="return auth.login();">登录</a> 或 ' +
                '<a href="http://www.imeelee.com/user/register" title="还没有注册？前往注册页面" class="register">注册</a></li><li class="sep"></li>'
            );
            $('#auth .admin').next().remove();
            $('#auth .admin').remove();
            $('#auth .help').nextAll('li').remove();
            $('#welcome').html('');
            alert('您已经成功退出会员系统！');
            auth.logoutSuccess();
        });
        return false;
    },
    refreshNew : function() { //刷新短消息数量
        if (auth.logined) {
            $.getJSON('/default/ajax/newCount', function(json){
                $('#welcome .msg').nextAll('li').remove();
                if (parseInt(json.msg) > 0) {
                    $('#welcome .msg').html('<a href="http://www.imeelee.com/msg/list" title="' + json.msg + ' 条新消息">短消息</a><span>(<font color=red>' + json.msg + '</font>)</span>');
                } else {
                    $('#welcome .msg').html('<a href="http://www.imeelee.com/msg/list" title="0 条新消息">短消息</a>');
                }
                if (parseInt(json.notice) > 0) {
                    $('#welcome').append('<li class="sep"></li><li class="notice"><a href="http://www.imeelee.com/notice/list" title="' + json.notice + ' 条新通知">' + json.notice + '</a></li>');
                }
            });
        }
        setTimeout(auth.refreshNew, 10000);
    }
};

/**
 * DOM Ready !
 */
$().ready(function(){
    //绑定顶部工具条事件
    $('#topbar .center').bindDropMenu('#topbar ul.center-menu', -10, -5);
    $('#topbar .msg').bindDropMenu('#topbar ul.msg-menu', -10, -5);

    //样式修正，兼容 IE6-
    $('input.text').hover(function(){$(this).addClass('texthover');}, function(){$(this).removeClass('texthover');});
    $('input.button').hover(function(){$(this).addClass('buttonhover');}, function(){$(this).removeClass('buttonhover');});
    $('textarea').hover(function(){$(this).addClass('textareahover');}, function(){$(this).removeClass('textareahover');});

    //修正邮件链接
    $('a.mailto').each(function(){
        this.innerHTML = this.innerHTML.replace(/_@_/, '@');
        this.href = "mailto:" + this.innerHTML;
    });

    //绑定 TABS 效果
    $('.jquery-tabs').tabs();

    //支付前检测浏览器
    $(".__PAYNOW").click(function(){
        if ($.browser.msie) {
            return true;
        } else {
            alert("非常抱歉，由于您选择的支付方式不支持非 IE 的浏览器，请切换到 IE 浏览器下再执行支付操作。");
            return false;
        }
    });

    $('a.delete').click(function(){return confirm('一旦删除将无法恢复，您确认要删除该记录吗？')});
});
