﻿/**
* 商品对比功能包
* @package product compare
*/

var cook_mall_compare_front = "cook_mall_compare_goods_";
var compare_num = "4";

var msg = Array();
//msg["please_select_then_compare"] = "请先选择商品再进行对比，谢谢！";
//msg["select_no_more_then_the_num"] = "对比商品最多只能选" + compare_num + "个哦！";
//msg["the_goods_already_have"] = "此商品已经在对比篮中了哦！";


function $$(id) {
    return document.getElementById(id) || false;
}

function writeCookie(name, value, hours) {
    var expire = "";
    if (hours != null) {
        expire = new Date((new Date()).getTime() + hours * 3600000);
        expire = "; expires=" + expire.toGMTString();
    }
    document.cookie = name + "=" + escape(value) + expire + "; path=/; domain=.88098585.com;";
}

function readCookie(name) {
    var cookieValue = "";
    var s_search = name + "=";
    if (document.cookie.length > 0) {
        offset = document.cookie.indexOf(s_search);

        if (offset != -1) {
            offset += s_search.length;
            end = document.cookie.indexOf(";", offset);
            if (end == -1) end = document.cookie.length;
            cookieValue = unescape(document.cookie.substring(offset, end))
        }
    }
    return cookieValue;
}

var comp = {};

comp.init_item = function(obj) {
    obj.onmouseover = function() {
        //obj.className = 'cl_c_act';
        //obj.getElementsByTagName('a')[0].style.display = 'block';
        obj.getElementsByTagName('a')[0].className = 'cl_c_act';
    }

    obj.onmouseout = function() {
        //obj.className = 'cl_c_nor';
        obj.getElementsByTagName('a')[0].className = 'cl_c_nor';
    }
}

//初始化对象
comp.init = function(sub_id) {
    if (!sub_id) sub_id = 0; //全局搜索用
    this.create_box('comp_box');
    this.counter = this.counterContainer.innerHTML = 0;
    this.sub_id = sub_id;
    this.last_sub_id = 0; //标记最后一次插入的商品SUBID
    this.subid_obj.value = this.sub_id;
    this.cookie_name = cook_mall_compare_front + this.sub_id;
    this.pro_arr = {};
    this.hasOnBeforeUnload = ('onbeforeunload' in window);
    var pro_str = readCookie(this.cookie_name);
    if (!pro_str) {
        this.hidden();
        return;
    }
    items_arr = pro_str.split('@@@');
    pro_num = items_arr.length;
    if (pro_num) {
        for (var i = 0; i < pro_num; i++) {
            one_item_arr = items_arr[i].split('|');
            cid = one_item_arr[0];
            this.add_item(one_item_arr);
        }
    } else {
        this.hidden();
    }
}

comp.create_box = function(comp_id) {

    this.comp_box = document.createElement('div');
    this.comp_box.id = comp_id;
    this.comp_box.className = 'compare_li';

    this.comp_form = document.createElement('form');
    with (this.comp_form) {
        action = '/pk.aspx';
        method = 'get';
        target = "_target";
        onsubmit = function() { return comp.exec() };
    }

    this.comp_top = document.createElement('div');
    with (this.comp_top) {
        id = 'comp_top';
        className = 'c_h';
        innerHTML = [
			'    <a href="javascript:comp.remove_all()" title="清空对比篮">清空</a>商品比较',
		].join('\r\n');

    }

    this.counterContainer = document.createElement('b');
    this.counterContainer.id = 'comp_num';

    var count_all = document.createElement('span');
    with (count_all) {
        innerHTML = [
			'    /' + compare_num + '',
		].join('\r\n');

    }

    this.comp_down = document.createElement('div');
    this.comp_down.className = 'c_b';

    this.itemContainer = document.createElement('span');
    this.itemContainer.id = 'comp_items';


    this.comp_foot = document.createElement('div');
    with (this.comp_foot) {
        className = 'compare_b';
        innerHTML = [
			'    <a style="cursor:pointer" onclick="doComp()"><input type=button value="对比"></a>',
		].join('\r\n');

    }
    this.subid_obj = document.createElement('input');
    with (this.subid_obj) {
        id = 'subid_obj';
        value = this.subcatid;
        name = 'subcatid';
        type = 'hidden';
    }
    this.comp_foot.appendChild(this.subid_obj);



    //this.comp_top.appendChild(this.counterContainer);
    //this.comp_top.appendChild(count_all);

    this.comp_down.appendChild(this.itemContainer);
    this.comp_down.appendChild(this.comp_foot);


    this.comp_form.appendChild(this.comp_top);
    this.comp_form.appendChild(this.comp_down);

    this.comp_box.appendChild(this.comp_form);
    document.body.appendChild(this.comp_box);
}

/**
* 删除所有对比商品
*/
comp.remove_all = function() {
    var items = this.itemContainer.getElementsByTagName('dl');
    var items_num = items.length;
    var cid_arr = [];
    if (items_num) {
        for (var k = 0; k < items_num; k++) {
            cid_arr[k] = items[k].id.substr(3);
        }
        for (var i = 0; i < cid_arr.length; i++) {
            cid = cid_arr[i];
            this.remove(cid);
        }
    }
}

comp.remove = function(id) {
    var checkbox = $$('cid_' + id);
    var cp_id = 'cp_' + id;
    var remvoe_item = $$(cp_id);
    delete comp.pro_arr['pro_' + id];
    this.itemContainer.removeChild(remvoe_item);
    this.counter--;
    this.counterContainer.innerHTML--;
    if (checkbox) checkbox.checked = false;
    this.hasOnBeforeUnload || this.destruct(); //不支持onbeforeunload事件的话，现在就处理COOKIE
}

comp.add_item = function(cid, pro_title, pro_link, img_src, sub_id) {
    if (typeof (cid) == 'object') {
        var option = cid;
        var cid = option[0];
        var pro_title = option[1];
        var pro_link = option[2];
        var img_src = option[3];
        var sub_id = option[4];
    } else {
        var option = [cid, pro_title, pro_link, img_src, sub_id];
    }
    if (this.last_sub_id) {
        if (sub_id != this.last_sub_id) {
            this.last_sub_id = sub_id;
            this.subid_obj.value = this.sub_id;
            this.remove_all();
        }
    } else {
        this.last_sub_id = sub_id;
    }

    if (this.pro_arr['pro_' + cid]) return;
    var this_item = document.createElement('dl');

    with (this_item) {
        id = 'cp_' + cid;
        innerHTML = [
			'      <a class="cl_c_nor" href="javascript:comp.remove(\'' + cid + '\');" title="从对比篮中移除该商品"></a>',
			'      <dt><a href="/ProductDetail.aspx?ProductID=' + pro_link + '" title="' + pro_title + '" target="_blank"><img src="' + img_src + '" width="80" height="65" /></a></dt>',
			'      <span style=\"width:100%;float:left\"><a href="/ProductDetail.aspx?ProductID=' + pro_link + '" title="' + pro_title + '" target="_blank">' + pro_title + '</a></span>',
			'      <input type="hidden" name="enid" value="' + pro_link + '">'
		].join('\r\n');
    }

    this.pro_arr['pro_' + cid] = option; //缓存变量
    this.init_item(this_item);
    this.counter++
    this.counterContainer.innerHTML++;
    this.itemContainer.appendChild(this_item);
    if ($$('cid_' + cid) && !$$('cid_' + cid).checked) {
        $$('cid_' + cid).checked = true;
    }
    fade(this_item, 0, 100);

    this.hasOnBeforeUnload || this.destruct(); //不支持onbeforeunload事件的话，现在就处理COOKIE

    return this_item;
}
comp.hidden = function() {
    this.comp_box.style.display = 'none';
}

comp.show = function() {
    this.comp_box.style.display = 'block';
}

comp.destruct = function() {
    var pro_join = [];
    if (this.pro_arr) {
        for (k in this.pro_arr) {
            pro_join.push(this.pro_arr[k].join('|'));
        }
        var pro_str = pro_join.join("@@@");
        writeCookie(this.cookie_name, pro_str);
    }
}

//执行对比
comp.exec = function() {
    if (this.counter == 0) {
        alert('请先选择要对比的商品~');
        //compare_alert(msg.please_select_then_compare);
        return false;
    }
    if (this.counter > compare_num) {
        alert('对比商品最多只能选'+compare_num+'个~');
        //compare_alert(msg.select_no_more_then_the_num);
        return false;
    }
    return true;
}
/**
* 透明渐变
* @author wiki <2009-02-14>
* @param element 元素
* @param opacity_from 渐变透明开始值
* @param opacity_to 渐变透明结束值
* @param callbackfunc 回调函数
* @return void
*/
function fade(element, opacity_from, opacity_to, callbackfunc) {
    var reduceOpacityBy = 5;
    var rate = 20;
    if (opacity_from <= 100 && opacity_from >= 0) {
        if (opacity_from < opacity_to) {//渐显
            opacity_from += reduceOpacityBy;
            if (opacity_from > opacity_to) opacity_from = opacity_to;
        } else if (opacity_from > opacity_to) {
            opacity_from -= reduceOpacityBy;
            if (opacity_from < opacity_to) opacity_from = opacity_to;
        }
        if (opacity_from > 100) opacity_from = 100;
        if (opacity_to > 100) opacity_to = 100;

        if (element.filters) {
            try {
                element.filters.item("DXImageTransform.Microsoft.Alpha").opacity = opacity_from;
            } catch (e) {
                element.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity=' + opacity_from + ')';
            }
        } else {
            element.style.opacity = opacity_from / 100;
        }
    }
    if (opacity_from > 0 && opacity_from < 100) {
        setTimeout(function() {
            fade(element, opacity_from, opacity_to, callbackfunc);
        }, rate);
    } else {
        typeof (callbackfunc) == 'function' && callbackfunc();
    }
}

/**
* 滚动跟随类
* @author wiki <2009-02-16>
*/
function scroll(settings) {
    var self = this;
    this.settings = settings;
    this.delta = this.settings.delta || 0.05; //滚动系数
    this.rate = this.settings.rate || 30; //速度
    this.items = [];
    this.addItem = function(element, x, y) {
        with (element.style) {
            position = 'absolute';
            left = typeof (x) == 'string' ? eval(x) : x;
            top = typeof (y) == 'string' ? eval(y) : y;
        }
        var newItem = {};
        newItem.obj = element;
        newItem.x = x;
        newItem.y = y;
        this.items[this.items.length] = newItem;
    }
    this.play = function() {
        for (var i = 0; i < self.items.length; i++) {
            var this_item = self.items[i];
            var this_item_x = typeof (this_item.x) == 'string' ? eval(this_item.x) : this_item.x;
            var this_item_y = typeof (this_item.y) == 'string' ? eval(this_item.y) : this_item.y;
            var doc = document.documentElement, body = document.body;
            var cw=document.body.clientWidth||document.documentElement.clientWidth;
            //var doc_left=cw-140;
            var doc_left = (doc && doc.scrollLeft-50 || body && body.scrollLeft-50 );
            var doc_top = (doc && doc.scrollTop || body && body.scrollTop || 0);
	        
            if (this_item.obj.offsetLeft != (doc_left + this_item_x)) {
                var dx = (doc_left + this_item_x - this_item.obj.offsetLeft) * self.delta;
                dx = (dx > 0 ? 1 : -1) * Math.ceil(Math.abs(dx));
                this_item.obj.style.left = (this_item.obj.offsetLeft + dx-5) + 'px';//edit by 51aspx
            }
            if (this_item.obj.offsetTop != (doc_top + this_item_y)) {
                var dy = (doc_top + this_item_y - this_item.obj.offsetTop) * self.delta;
                dy = (dy > 0 ? 1 : -1) * Math.ceil(Math.abs(dy));
                this_item.obj.style.top = (this_item.obj.offsetTop + dy+20) + 'px';//edit by 51aspx
            }
        }
        if (this_item.obj.style.display == 'block' || this_item.obj.style.display == '')
            window.setTimeout(function() { self.play() }, self.rate);
    }
}

/**
* checkbox 添加对比商品
*/
function add_comp(obj, pro_name, pro_link, img_src, subcatid) {
    if (comp.comp_box.style.display == 'none') {
        comp.comp_box.style.display = 'block';
        comp_scroll.play();
    };

    if (typeof (obj) == 'object') {
        var cid = obj.value;
    } else {
        var cid = obj;
    }

    if (obj.checked) {//添加
        if (comp.counter >= compare_num) {
            obj.checked = false;
            alert('对比商品不能超过'+compare_num+'个~');
            //compare_alert(msg.select_no_more_then_the_num);
            return false;
        }
        var result_obj = comp.add_item(cid, pro_name, pro_link, img_src, subcatid);
        if (typeof (result_obj) != 'object') {
            obj.checked = false;
            alert('此商品已经在对比篮中了~');
            //compare_alert(msg.the_goods_already_have);
            return false;
        }
    } else {//删除
        comp.remove(cid);
    }
}

/**
* 对比已钩选的商品
*/
function doComp() {
    if (comp.subid_obj.value == 0) {
        comp.subid_obj.value = comp.last_sub_id;
    }

    comp.exec() && comp.comp_form.submit();
    //comp.exec() && location.href("/pk.aspx");
    return false;
}

function compare() {
    //window.onload = function () {
    // comp.init(subcatid);
    var cw=document.body.clientWidth||document.documentElement.clientWidth;
    
    comp.init(0);
    comp_scroll = new scroll({ delta: 0.3, rate: 50 });
    //comp_scroll.addItem(comp.comp_box, cw-50, 20);
    comp_scroll.addItem(comp.comp_box, 60, 130);
    comp_scroll.play();
    //离开页面时触发
    window.onbeforeunload = function() {
        comp.destruct();
    }
    //}
}

//重置 弹出窗口
function compare_alert(content) {
    popbox.content = content;
    popbox.pop();
    popbox.popbox_close();

}