/**
 * Khởi tạo prototype xử lý trang taobao.com
 * @constructor
 * @author Dung tao
 */
function Taobao($) {
    this.$ = $;

    // @TODO Chèn dữ nút
    this.initDataTrader();
}

Taobao.prototype.initDataTrader = function() {
    this.DOM = {
        pageTitle: "title",
        itemName: ".tb-main-title",
        itemAvatar: "#J_ImgBooth",
    };
};

// get DOM
Taobao.prototype.getData = function(e) {
    var _self = this;

    var _title = _self.get_name();
    var itemName = _title.textContent;
    // if(itemName == "" || typeof itemName == "undefined" || itemName == null){
    //     itemName = _title.textContent;
    // }


    var item_code = _self.get_item_code();
    var price_promotion = _self.get_price_promotion();
    var price_origin = _self.get_origin_price();

    var itemAvatar = (_self.$(_self.DOM.itemAvatar).attr('src')) ? _self.$(_self.DOM.itemAvatar).attr('src') : '';

    if (itemAvatar != '' && !/^https?:\/\//i.test(itemAvatar)) {
        itemAvatar = 'https:' + itemAvatar;
    }

    //thumb images
    var thumb_images_arr = [];
    _self.$("#J_UlThumb .tb-pic img").each(function(){
        var data_image = _self.$(this).attr('data-src');
        if( typeof data_image != 'undefined' && data_image.length > 0){
            data_image =  data_image.replace('.jpg_50x50', '');
            thumb_images_arr.push(data_image);
        }
    });


    var thumb_video_image = _self.$("#J_UlThumb #J_VideoThumb img").attr('src');
    if(typeof thumb_video_image != 'undefined' && thumb_video_image.length > 0){
        thumb_video_image = thumb_video_image.replace('.jpg_400x400', '');
    }
    var thumb_video = {
        image: thumb_video_image,
        video: _self.$(".tb-video video source").attr('src')
    }


    var attr_option_arr = [];
    _self.$(".tb-skin dl.J_Prop").each(function(){
        var attr_name = _self.$(this).find("dt.tb-property-type").text();

        var option_arr = [];
        if(attr_name.length > 0){
            _self.$(this).find("dd ul.J_TSaleProp li").each(function(){
                var option_obj = {
                    option_name: _self.$(this).find("a").text(),
                    option_val: _self.$(this).attr('data-value'),
                    attr_style : _self.$(this).find("a").attr('style')
                };
                option_arr.push(option_obj);
            });
        }

        if(option_arr.length > 0){
            var attr_obj = {
                name: attr_name,
                option_data: option_arr
            };
            attr_option_arr.push(attr_obj);
        }
    });


    var detail_infor_arr = [];
    _self.$("#attributes ul.attributes-list li").each(function(){
        var detail_obj = {
            title: _self.$(this).attr('title'),
            text: _self.$(this).text()
        }

        detail_infor_arr.push(detail_obj);
    });

    var description_img_arr = [];
    _self.$("#description #J_DivItemDesc img").each(function(){
        var data_image = _self.$(this).attr('src');
        description_img_arr.push(data_image);
    });

    var shop_link = _self.$(".tb-shop-name").find("a").attr('href');
    if(shop_link == "" || typeof shop_link == "undefined" || shop_link == null){
        shop_link = _self.$("a.shop-name-link").attr('href');
    }
    if(shop_link != ''){
        shop_link = shop_link.replace('//', '');
    }
    var feedback_arr = [];
    var rating = 0; //_self.$("#J_Reviews .tm-rate .rate-score strong").text();
    var total_order = _self.$(".tb-counter .tb-sell-counter strong").text();

    _self.$("ul li.kg-rate-ct-review-item").each(function(){

        var feedback_img_arr = [];
        _self.$(this).find(".review-details .tb-rev-item .tb-rev-item-media ul.kg-photo-viewer-thumb-bar li.photo-item img").each(function(){
            var link_img = _self.$(this).attr("src");
            if(link_img != ''){
                feedback_img_arr.push(link_img);
            }

        });

        var feedback_obj = {
            feedback_id : _self.$(this).find(".review-details .tb-rev-item").data('id'),
            user_avatar: _self.$(this).find(".from-whom img.avatar").attr("src"),
            user_name: _self.$(this).find(".from-whom div").text(),
            title: _self.$(this).find(".review-details .tb-rev-item .J_KgRate_ReviewContent").text(),
            image: feedback_img_arr,
            time: _self.$(this).find(".review-details .tb-rev-item .tb-r-info span.tb-r-date").text()
        }
        feedback_arr.push(feedback_obj);
    });

    return {
        site: 'taobao',
        shop_link: shop_link,
        item_code: item_code,
        link: _self.$('link[rel="canonical"]').attr('href'),
        name: itemName,
        avatar: itemAvatar.trim(),
        thumb_images_arr: thumb_images_arr,
        thumb_video: thumb_video.video,
        thumb_video_image: thumb_video.image,
        price_promotion: price_promotion,
        price_origin: price_origin,
        attr_option_arr: attr_option_arr,
        detail_infor_arr: detail_infor_arr,
        description_img_arr: description_img_arr,
        feedback_rate: rating,
        feedback_content: feedback_arr,
        total_order: total_order
    }

};


Taobao.prototype.get_name = function(e){
    try{
        var _title = null;
        if (document.getElementsByClassName("tb-main-title").length > 0) {
            _title =  document.getElementsByClassName("tb-main-title")[0];
        }

        if (_title == null && document.getElementsByClassName("tb-detail-hd").length > 0) {
            var h = document.getElementsByClassName("tb-detail-hd")[0];
            if (h.getElementsByTagName('h3').length > 0 && h != null) {
                _title = h.getElementsByTagName('h3')[0];
            }else{
                _title = h.getElementsByTagName("h1")[0];
            }
        }

        if (_title.textContent == "" && document.getElementsByClassName("tb-tit").length > 0) {
            _title = document.getElementsByClassName("tb-tit")[0];
        }
        if (_title.textContent == "") {
            _title = document.querySelectorAll('h3.tb-item-title');
            if (_title != null) {
                _title = _title[0];
            }else{
                _title = document.getElementsByClassName('tb-item-title');
                if(_title.length > 0){
                    _title = _title[0];
                }
            }
        }
        return _title;
    }catch(ex){
        return null;
    }
};

Taobao.prototype.get_price_promotion = function(e){
    var span_price = null;
    var normal_price = document.getElementById('J_StrPrice');
    if(normal_price == null){
        normal_price = document.getElementById("J_priceStd");
    }

    if(normal_price == null) {
        normal_price = document.getElementById('J_StrPriceModBox');
    }

    if(normal_price == null){
        normal_price = document.getElementById('J_PromoPrice');
    }

    var promotion_price = document.getElementById('J_PromoPrice');

    var price = 0;
    if(promotion_price == null){
        promotion_price = normal_price;
    }

    if(promotion_price != null) {
        try{

            if(promotion_price.getElementsByClassName('tm-price').length > 0) {
                span_price = promotion_price.getElementsByClassName('tm-price');
                if(span_price != null && span_price != "" && span_price != "undefined"){
                    price = span_price[0].textContent.match(/[0-9]*[\.,]?[0-9]+/g);
                }
            }else if(promotion_price.getElementsByClassName('tb-rmb-num').length > 0){
                span_price = promotion_price.getElementsByClassName('tb-rmb-num');
                if(span_price != null && span_price != "" && span_price != "undefined"){
                    price = span_price[0].textContent.match(/[0-9]*[\.,]?[0-9]+/g);
                }
            }

            /*
             * fix công cụ: Link sản phẩm không hiện giá VND
             * http://world.taobao.com/item/523372039199.htm?spm=a312a.7700714.0.0.IJ566v#detail
             *
             * */
            if(!price){
                promotion_price = normal_price;
            }
            if(promotion_price.getElementsByClassName('tm-price').length > 0) {
                span_price = promotion_price.getElementsByClassName('tm-price');
                if(span_price != null && span_price != "" && span_price != "undefined"){
                    price = span_price[0].textContent.match(/[0-9]*[\.,]?[0-9]+/g);
                }
            }else if(promotion_price.getElementsByClassName('tb-rmb-num').length > 0){
                span_price = promotion_price.getElementsByClassName('tb-rmb-num');
                if(span_price != null && span_price != "" && span_price != "undefined"){
                    price = span_price[0].textContent.match(/[0-9]*[\.,]?[0-9]+/g);
                }
            }

        }catch(e){
            price = 0;
        }
    }

    return price;
}

Taobao.prototype.get_origin_price = function(e){
    var _self = this;
    try{
        var str_price = _self.$('#J_StrPrice');
        var origin_price = str_price.find('.tm-price');

        if(origin_price == null || origin_price.length == 0){
            origin_price = str_price.find('.tb-rmb-num');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_priceStd').find('.tb-rmb-num');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_priceStd').find('.tm-price');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_StrPriceModBox').find('.tm-price');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_StrPriceModBox').find('.tb-rmb-num');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_PromoPrice').find('.tm-price');
        }

        if(origin_price == null || origin_price.length == 0){
            origin_price = _self.$('#J_PromoPrice').find('.tb-rmb-num');
        }

        var price = origin_price.text();
        price = price.match(/[0-9]*[\.,]?[0-9]+/g);

        return price;
    }catch(ex){
        throw Error(ex.message+ " Can't get origin price function getOriginPrice");
    }
};

Taobao.prototype.get_item_code = function(e){

    var item_id = 0;
    var home = window.location.href;
    var dom;
    //1. Lấy trên dom
    if(!item_id){
        try{

            dom = document.getElementsByName("item_id");
            if(dom.length){
                item_id = dom[0].value;
            }else{
                item_id = document.getElementsByName("item_id_num")[0].value;
            }

        }catch(e){

        }
    }
    //2. Lấy trên link dạng http://world.taobao.com/item/521828428176.htm?*
    if(!item_id){
        try{
            var temp = home.split('.htm')[0];
            item_id = temp.split('item/')[1];
        }catch(e){

        }
    }

    //3. Lấy params trên url dạng ?spm=a312a.7728556.2015080705.14.fbm100&amp;id=521985720964&amp;scm=1007.12006.12548.i522577577280&amp;pvid=34d586a7-1587-44bb-8b07-1fb66252488c
    if(!item_id){
        try{
            item_id = this.common_tool.getParamsUrl('id', home);
        }catch(e){

        }
    }

    //console.info("item_id: " + item_id);
    return item_id;

};






Taobao.prototype.getList = function(e) {
    var _self = this;

    var item_arr = [];
    _self.$(".shop-hesper-bd .item").each(function(){
        var detail_obj = {
            code: _self.$(this).attr('data-id'),
            link: _self.$(this).find(".photo a").attr("href"),
            img: _self.$(this).find(".photo a img").attr("src"),
            name: _self.$(this).find(".photo a img").attr("alt")
        };
        item_arr.push(detail_obj);
    });

    return {
        site: 'taobao',
        item_list : item_arr
    }
    
}

