﻿var undefined = undefined;

//set cookie:   $.cookie(name,value,[expires,path,domain,secure]);expires=1 means expires is 1 day
//get cookie:   $.cookie(name);
//delete cookie:$.cookie(name,null);

$.cookie = function(name, value, expires, path, domain, secure) {
    if (typeof value != 'undefined') {
        if (value === null) {
            value = '';
            expires = -1;
        }
        var c = name + '=' + value;
        if (expires) {
            c += ';expires=' + new Date(new Date().getTime() + expires * 86400000).toUTCString();
        }
        c += ';path=/';
        if (domain) {
            c += ';domain=' + domain;
        }
        if (secure) {
            c += ';secure';
        }
        //alert(c);
        document.cookie = c;
    } else {
        var rs = ';?' + name + '=([^;]*);?';
        var r = new RegExp(rs);
        if (r.test(document.cookie)) {
            return RegExp['$1'];
        } else {
            return null;
        }
    }
}

var encodeUni = function(s) { return encodeURIComponent(s); }
var decodeUni = function(s) { return decodeURIComponent(s); }

/*计时器*/
var Timer = function() {
    var t0, t1;
    this.start = function() {
        this.t0 = new Date();
    };
    this.stop = function() {
        this.t1 = new Date();
    };
    this.elapse = function() {
        return this.t1 - this.t0;
    }
}

/*添加命名空间*/
var addNameSpace = function(name) {
    var c = window;
    if (typeof (name) === "string" && name.length != 0) {
        var f = c;
        var d = name.split("."), l = d.length;
        for (var i = 0; i < l; i++) {
            var e = d[i];
            if (!c[e]) {
                c[e] = {};
            }
            f = c = c[e];
        }
    }
}


function isNumber(str) {
    return (/^[+|-]?\d+$/.test(str));
}


function checkTel(val) {
    var checkValue = val;
    if(checkValue.length>18) return false;
    if (/^([0-9]|-|[+])*$/.test(checkValue)) return true;
    return false;
}

function checkNum(val) {
    var checkValue = val;
    if (/^([0-9])*$/.test(checkValue)) return true;
    return false;
}

function checkCNEN(val) {
    var checkValue = val;
    if (/^([\u4e00-\u9fa5]|[a-z]|[A-Z])*$/.test(checkValue)) return true;
    return false;
}

function checkAddress(val, e) {
    var checkValue = val;
    if (/^([\u4e00-\u9fa5]|[a-z]|[A-Z]|[0-9]|[ -_\(\)])*$/.test(checkValue)) return true;
    return false;
}

//模板替换
if (!String.prototype.template)
    String.prototype.template = function() {
        var args = arguments;
        return this.replace(/\{(\d+)\}/g, function(m, i) {
            return args[i];
        });
    }

//可以加上注释
if (!String.prototype.template2)
    String.prototype.template2 = function() {
        var args = arguments;
        return this.replace(/\{\w*?:(\d+)\}/g, function(m, i) {
            return args[i];
        });
    }

//给js地址加随机数
if (!String.prototype.randomUrl)
    String.prototype.randomUrl = function() {
        _this = this;
        return [this, Math.random()].join(_this.indexOf("?") > 0 ? "&" : "?");
    }

if (!String.prototype.repeat)
    String.prototype.repeat = function(times) {
        return new Array(times + 1).join(this);
    }
    
if(!String.prototype.Trim || !String.prototype.trim)
    String.prototype.Trim= String.prototype.trim = function(){  
        return this.replace(/(^\s*|\s*$)/g,"");
    }


var merge = function(dst, src, preserveExisting) {
    for (var i in src) {
        if (!preserveExisting || dst[i] === undefined)
            dst[i] = src[i];
    }
    return dst;
}

function isArray(o) {
    return Object.prototype.toString.call(o) === '[object Array]';
}

if (![].aggregate) {
    Array.prototype.aggregate = function(iterator, from) { from = from || 0; if (from > (this.length - 1)) return ""; var sum = []; for (var i = from; i < this.length; i++) { sum[sum.length] = iterator.call(this[i], i, this[i]); } return sum.join(""); };
}

if (![].each) {
    Array.prototype.each = function(iterator, from) { from = from || 0; if (from > (this.length - 1)) return []; var ret = []; for (var i = from; i < this.length; i++) { ret[ret.length] = iterator.call(this[i], i, this[i]); } return ret; };
}

if (![].firstOrDefault)
    Array.prototype.firstOrDefault = function(iterator, from) { from = from || 0; if (from > (this.length - 1)) return null; var ret = null; for (var i = from; i < this.length; i++) { if (iterator.call(this[i], i, this[i])) { ret = this[i]; break; } } return ret; };

if (![].indexOf) {
    Array.prototype.indexOf = function(obj, start) {
        var found = -1;
        for (var i = (start || 0); i < this.length; i++) {
            if (this[i] == obj) {
                return i;
            }
        }
        return found;
    }
}

var Ulity = {
    E: function(a) { return jQuery(this.E2(a)); },
    E2: function(a) { return document.getElementById(a); }
}

/*Range*/

var Range = {
    create: function(start, end, step) {
        var ret = [];
        if (start < 0 || end < 0 || step < 0)
            return ret;
        step = step || 1;
        ret[0] = start;
        while ((start += step) < end) {
            ret[ret.length] = start;
        }
        ret[ret.length] = end;
        return ret;
    }
}

/*Round*/

var Round = function(a, step) {
    var t = [];
    var step = step || 1;
    t = a;
    this.nextVal = function(cur) {
        var i = t.indexOf(cur);
        var next = i + step;
        return t[next >= t.length ? (next - t.length) : next];
    };
};

function LoadScript(url) {
    document.write('<scr' + 'ipt type="text/javascript" src="' + url + '"><\/scr' + 'ipt>');
}

/*
    var innerArr = ["a","b","c"];
    var round = new Round(innerArr);
    alert(round.nextVal("a"));
    alert(round.nextVal("b"));
    alert(round.nextVal("c"));

    可以在多个Class之间切换
*/
(function(R) {
    R.fn.toggleClass2 = function(arrClasses) {

        var innerArr = arrClasses;
        var round = new Round(innerArr);

        return this.each(function() {
            var l = innerArr.length;
            var cur = null;
            while (l--) {
                if (jQuery.className.has(this, innerArr[l])) {
                    cur = innerArr[l];
                    break;
                }
            }
            if (cur != null) {
                jQuery.className["remove"](this, cur);
                jQuery.className["add"](this, round.nextVal(cur));
            }
        });
    };
})(jQuery);

/*
    pagerBase 分页,详细页面的评论和帮我挑详细页面的评论使用
*/
var pagerBase = {
    object: null,
    list: null,
    pager: null,
    linkTemplate: "<a href='javascript:void(0)' onclick='{2}' class='pager {0}'>{1}</a>",
    pageSize: 5,
    currentPage: 0,
    count2: function() { return 0; }, //总数    
    url: null,

    loadPage: function(pageIndex) {//alert(this.object);
        pageIndex = pageIndex || 0;
        this.currentPage = pageIndex;
        var pageStart = pageIndex * this.pageSize, pageEnd = pageStart + this.pageSize;
        var _this = this;
        this.onajax();
        this.list.load(this.geturl(pageStart, pageEnd), {}, function() {
            _this.oninit();
            _this.preRender5();
            _this.onload();
        });
    },
    loadCurrentPage:function(){
        this.loadPage(this.currentPage);
    },
    geturl: function(pageStart, pageEnd) {
        return this.url.template(pageStart, pageEnd);
    },
    onajax: function() { },
    oninit: function() { },
    onload: function() { },
    preRender3: function() {/*分页一*/
        var count = this.count2();
        var pageIndex = parseInt(this.currentPage);
        recordCount = count;

        var pageCount = parseInt(recordCount / this.pageSize);

        if (recordCount % this.pageSize > 0)
            pageCount++;

        if (pageIndex > pageCount - 1)
            pageIndex = pageCount - 1;

        if (pageIndex < 0)
            pageIndex = 0;

        /*生成链接*/
        var html = "";

        if (recordCount != 0) {
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(0);return false;'>首页</a>";
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage > 0 ? this.currentPage - 1 : 0) + ");return false;'>上一页</a>";
        }

        for (var i = 0; i < pageCount; i++) {
            var pageStart = i * this.pageSize, pageEnd = pageStart + this.pageSize;
            var current = pageIndex == i;
            html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
        }

        if (recordCount != 0) {
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage >= pageCount - 1 ? pageCount - 1 : this.currentPage + 1) + ");return false;'>下一页</a>";
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (pageCount - 1) + ");return false;'>末页</a>";
        }

        this.pager.html(html);
    },
    preRender4: function() {/*分页二*/
        var count = this.count2();
        var pageIndex = parseInt(this.currentPage);
        recordCount = count;

        var pageCount = parseInt(recordCount / this.pageSize);

        if (recordCount % this.pageSize > 0)
            pageCount++;


        if (pageIndex > pageCount - 1)
            pageIndex = pageCount - 1;

        if (pageIndex < 0)
            pageIndex = 0;

        /*生成链接*/
        var html = "";

        if (recordCount != 0) {
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(0);return false;'>首页</a>";
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage > 0 ? this.currentPage - 1 : 0) + ");return false;'>上一页</a>";
        }

        if (pageIndex <= 4) {
            if (pageCount > 5) {
                for (var i = 0; i < 5; i++) {
                    var current = pageIndex == i;
                    html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
                }
                html += "...";
            } else {
                for (var i = 0; i < pageCount; i++) {
                    var current = pageIndex == i;
                    html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
                }
            }
        } else {
            if ((pageCount - pageIndex) > 2) {
                html += "...";
                for (var i = pageIndex - 2; i <= pageIndex + 2; i++) {
                    var current = pageIndex == i;
                    html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
                }
                html += "...";
            } else {
                html += "...";
                for (var i = pageIndex - 4; i <= pageCount; i++) {
                    var current = pageIndex == i;
                    html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
                }
            }
        }

        if (recordCount != 0) {
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage >= pageCount - 1 ? pageCount - 1 : this.currentPage + 1) + ");return false;'>下一页</a>";
            html += "<a href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (pageCount - 1) + ");return false;'>末页</a>";
        }
        //alert(this.pager.length)
        this.pager.html(html);
    },
    preRender5: function() {/*分页三*/
        var count = this.count2();
        var pageIndex = parseInt(this.currentPage);
        recordCount = count;

        var pageCount = parseInt(recordCount / this.pageSize);

        if (recordCount % this.pageSize > 0)
            pageCount++;


        if (pageIndex > pageCount - 1)
            pageIndex = pageCount - 1;

        if (pageIndex < 0)
            pageIndex = 0;

        /*生成链接*/
        var html = "<div class=\"pre_next pre_next_share\">";

        if (pageIndex == 0) {
            html += "<a class='pre_page' href='javascript:void(0)' onclick='return false;'></a>";
        } else {
            html += "<a class='pre_page' href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage > 0 ? this.currentPage - 1 : 0) + ");return false;'></a>";
        }

        if (pageIndex == 0) {
            html += "<a class='pager on' href='javascript:void(0)' onclick='" + this.object + ".loadPage(0);return false;'>1</a>";
        } else {
            html += "<a class='pager' href='javascript:void(0)' onclick='" + this.object + ".loadPage(0);return false;'>1</a>";
        }

        if (pageIndex == 0) {

            for (var i = 1; i < (pageCount > 5 ? 5 : pageCount); i++) {
                var current = pageIndex == i;
                html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
            }

            if (pageCount > 5) {
                html += "<span>...</span>";
                html += "<a class='pager' href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (pageCount - 1) + ");return false;'>末页</a>";

            }

        }
        else if (pageIndex <= 3 && pageIndex > 0) {
            for (var i = 1; i < (pageCount > 5 ? 5 : pageCount); i++) {
                var current = pageIndex == i;
                html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");
            }

            if (pageCount > 5) {
                html += "<span>...</span>";
                html += "<a class='pager' href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (pageCount - 1) + ");return false;'>末页</a>";

            }
        }
        else if (pageIndex > 3) {
            html += "<span>...</span>";

            for (var i = pageIndex - 2; i <= ((pageCount - pageIndex - 1 > 2) ? (pageIndex + 2) : (pageCount - 1)); i++) {
                var current = pageIndex == i;
                html += this.linkTemplate.template(current ? "on" : "", i + 1, current ? "return false;" : this.object + ".loadPage(" + i + ");return false;");

            }

            if (pageCount - pageIndex - 1 > 2) {
                html += "<span>...</span>";
                html += "<a class='pager' href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (pageCount - 1) + ");return false;'>末页</a>";

            }

        }

        if ((pageIndex + 1) == pageCount) {
            html += "<a class='next_page' href='javascript:void(0)' onclick='return false;'></a>";
        } else {
            html += "<a class='next_page' href='javascript:void(0)' onclick='" + this.object + ".loadPage(" + (this.currentPage >= pageCount - 1 ? pageCount - 1 : this.currentPage + 1) + ");return false;'></a>";

        }

        html += "<label>共" + pageCount + "页</label>";

        this.pager.html(html);
    }
}



addNameSpace("Ac.Common");
addNameSpace("Ac.Config");
addNameSpace("Ac.Product");
addNameSpace("Ac.Page");
addNameSpace("Ac.Order");

Ac.Config.Favorites = "/Customer/Favorites";

/*登录与验证*/

Ac.Common.Authentication = {
    /*google track code*/
    /*域名shop.msn.com.cn下用第一个，msn.yobrand.com用第二个*/
    Code :["onClick=\"javascript: pageTracker._trackPageview ('/outgoingsignup/yobrand.com');\"","onClick=\"javascript: pageTracker._trackPageview ('/outgoingsignup/yobrand.com');\""],
    OnLogin: "<a href='http://msn.yobrand.com/space/{userid:1}' title='{userfullname:2}' class='user_name'>{username:0} <span>欢迎回来</span></a>" +
            "<div class='myaccount'>" +
             "   <a href='http://msn.yobrand.com/account' class='account'>我的账户</a>(<a href='https://ids.msn.com.cn/rpsservice/signout.aspx?c=1001&v=1000&rt=http://www.yobrand.com&o={location:3}'>登出</a>)" +
              "  <ul id='account_list'>" +
               "     <li class='first'><a href='http://msn.yobrand.com/account' class='account_wbg'>我的账户</a>(<a href='https://ids.msn.com.cn/rpsservice/signout.aspx?c=1001&v=1000&rt=http://www.yobrand.com&o={location:3}'>登出</a>)</li>" +
                "    <li><a href='http://msn.yobrand.com/order'>订单中心</a></li>" +
                 "   <li><a href='http://msn.yobrand.com/customer/point'>我的积分</a></li>" +
                  "  <li><a href='http://msn.yobrand.com/customer/address'>地址簿</a></li>" +
               " </ul>" +
            "</div>" +
           " <a href='http://msn.yobrand.com/customer/favorites' class='favrite'>收藏夹</a>" +
           " <a href='http://msn.yobrand.com/space/{userid:1}' class='user_head'><img src='http://test.yobrand.com/face/{userid:1}' /></a>",
    OnRegister: "<a class='user_head'><img src='" + Ac.Config.WebStaticServer + "/content/site/images/user_head.gif' /></a>" +
            "<p>如果您有MSN帐号则无需注册</p>" +
            "<a href='https://ids.msn.com.cn/rpsservice/Registration.aspx?c=1001&v=1000&rt=http://www.yobrand.com' class='sign' {googlecode:0}>注册</a>" +
            "<a href='https://ids.msn.com.cn/rpsservice/signin.aspx?c=1001&v=1000&rt=http://www.yobrand.com&o={location:1}' class='btn'><img src='" + Ac.Config.WebStaticServer + "/content/site/images/login_msn.gif' /></a>",
    LoadGUI: function() {
        if (Ac.Page.IsLogin != undefined) {
            if (Ac.Page.IsLogin) {
                $("#checklogin").removeClass("wait_for").addClass("loginout").html(this.OnLogin.template2(Ac.Page.SubUserName, Ac.Page.UserId,Ac.Page.UserName,location));
                $("#myorder").attr("href", "http://msn.yobrand.com/order").show();

            } else {
                var loc = location.href.indexOf("shop.msn.com.cn");
                var code = loc > -1 ? this.Code[0] : this.Code[1];
                $("#checklogin").removeClass("wait_for").addClass("login").html(this.OnRegister.template2(code,location));
                $("#myorder").attr("href", "#").hide();
            }
            $("#mycart").text(Ac.Page.CartCount);
        }
    }
};



Ac.Common.Tip = {
    tip: null, /*tip*/
    Ele: null, /*current element*/
    Isinitialized: false, /*initialized status*/
    PreInitialize:function(){},
    Initialize: function() {
        if (this.Isinitialized == false) {   
            this.PreInitialize();
            this.Isinitialized = true;
        }
    },
    PreRender : function(data,pos){},
    Show: function(data, pos) {
        if (!this.Ele) return;
        
        this.Initialize();
        
        this.PreRender(data,pos);
        
        this.tip.show();
    },
    Hide: function() {
        this.tip.hide();
    }
};

/*收藏Tip*/

Ac.Common.Tip.Favorite = {
    _config: ["商品成功加入收藏夹", "已经添加此商品", "收藏失败"],
    _html: "<div id='add_tocate'>" +
               " <span onclick='javascript:Ac.Common.Tip.Favorite.Hide()'>×</span>" +
                "<h2 id='ac_common_tip_msg'></h2>" +
                "<a href='/customer/favorites' class='imp'>去我的收藏夹></a>" +
            "</div>",
    _images: [Ac.Config.WebStaticServer + "/content/site/images/add_tomyr.gif", Ac.Config.WebStaticServer + "/content/site/images/add_tomyrr.gif"],
    _sucess: true, /*pre status*/
    tiptext: null, /*tiptext word*/
    PreInitialize : function() {
        $(document.body).append(this._html);
        this.tip = $("#add_tocate");
        this.tiptext = $("#ac_common_tip_msg");
    },
    PreRender: function(data, pos) {

        pos = pos || { left: 0, top: 0 };
        
        if($.browser.msie){
            pos.top-=10;
        }

        var position = { left: $(this.Ele).offset().left, top: $(this.Ele).offset().top };

        this.tip.hide();
        this.tip.css({ left: position.left + pos.left, top: position.top + pos.top });

        if (data == 'alreadyexist') {
            if (!this._sucess) {
                this.tiptext.css("background-image","url(" + this._images[0] + ")");
                this._sucess = true;
            }
            this.tiptext.html(this._config[1]);
        } else if (parseInt(data) > 0) {
            if (!this._sucess) {
                this.tiptext.css("background-image","url(" + this._images[0] + ")");
                this._sucess = true;
            }
            this.tiptext.html(this._config[0]);

            /*详细页面 首次 收藏成功 数量+1*/
            var detailfavoriate1 = $("#DetailFavoriate1");
            detailfavoriate1.html(parseInt(detailfavoriate1.html()) + 1);
        } else {
            if (this._sucess) {
                this.tiptext.css("background-image","url(" + this._images[1] + ")");
                this._sucess = false;
            }
            this.tiptext.html(this._config[2]);
        }
    }
};

merge(Ac.Common.Tip.Favorite,Ac.Common.Tip,true);

/*购物袋页面结算按钮弹出的提示信息*/
Ac.Common.Tip.Cart = {
    _config : "请先移除已下架或缺货的商品，再进行结算。",
    _html: "<div id='add_tocate'>" +
               " <span onclick='javascript:Ac.Common.Tip.Cart.Hide()'>×</span>" +
                "<h2 id='ac_common_tip_msg2' style='font-size:12px;margin-top:5px;line-height:18px'></h2>" +
            "</div>",
    _images: [Ac.Config.WebStaticServer + "/content/site/images/add_tomyrr.gif"],
    tiptext : null,
    PreInitialize : function() {
        $(document.body).append(this._html);
        this.tip = $("#add_tocate");
        this.tiptext = $("#ac_common_tip_msg2");
    },
    PreRender: function(data, pos) {

        pos = pos || { left: 0, top: 0 };
        
        if($.browser.msie){
            pos.top-=10;
        }

        var position = { left: $(this.Ele).offset().left, top: $(this.Ele).offset().top };

        this.tip.hide();
        this.tip.css({ left: position.left + pos.left, top: position.top + pos.top });

        this.tiptext.css("background-image","url(" + this._images[0] + ")");
        this.tiptext.html(this._config);

    }
}

merge(Ac.Common.Tip.Cart,Ac.Common.Tip,true);

/*
    var Tabs = {tabs:null,conts:null}; 
    merge(Tabs,Ac.Common.Tab,true);
    Tabs.tabs = $("li","#DetailBind");
    Tabs.conts = $(".sets_c","#DetailBind");
    Tabs.init();
    
    实现Tab切换的对象,详细页面的捆绑会用到
*/
Ac.Common.Tab = {
    tabs: null,/*tab*/
    conts: null,/*content*/
    className: { current: "on" },/*css class*/
    event : "mouseover",/*触发事件*/
    init: function() {
        var _this = this;

        this.tabs.each(function(i, a) {
            $(a).bind(_this.event,null,function() {
                _this.render(i);
            });
        });
        
        /*如果存在则初始化第一个*/
        if(this.tabs.length>0 && this.conts.length>0)
            _this.render(0);
    },
    render: function(i) {
        this.tabs.removeClass(this.className.current);
        $(this.tabs[i]).addClass(this.className.current)
        this.conts.hide();
        $(this.conts[i]).show();
    }
};



