﻿

jQuery.fn.Price = function (config) {


    var exceptionProduct = { "products": [
       { "productID": "10310-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "60103-1-Ig", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "11141-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "18470-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "18495-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "19944-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "19945-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "19946-1-AP", "Country": "Germany", "Note": "Not available in Germany." },
       { "productID": "19947-1-AP", "Country": "Germany", "Note": "Not available in Germany." }
    ]
    };

    config = jQuery.extend({
        id: null,    //ID
        catNo: null,
        className: 'CountryPrice',
        row: null,
        isFree: -1, //>0:is free sample <0:not
        btnShow: true, //show 'add to cart'
        proType: -1, //1:ab,2:sab,3:ag
        callback: function () { return false; }
    }, config || {});

    return this.each(function () {

        var me = $(this);

        init = function () {
            userFrom(make);
        };

        make = function () {
            $.getJSON("../Handler/SystemHandler.ashx?r=" + Math.random(),
            { func: 'GetCountry' },
            function (res) {
                //1. from cookie
                var countrySelected = $.cookie('ptg_user_country_selected');
                //2. from login info
                if (countrySelected == null && $.cookie('ptg_user_info_login') != null)
                    countrySelected = $.cookie('ptg_user_info_login').Country;
                //3. from page response
                if (countrySelected == null && $.cookie('ptg_user_web_from') != null)
                    countrySelected = $.cookie('ptg_user_web_from').CountryName;

                var str = new Array();
                str.push('<table border="0" class="' + config.className + '"><tbody>');
                str.push('<tr height="20"><th width="130">Country/Region</th><th width="70">Size</th><th width="60">Price</th><th width="95">Freight/Packing</th></tr>');
                str.push('<tr><td height="30">');
                str.push('<select name="select" id="country" style="width: 126px;height: 20px;">');
                str.push('<option agent="" value="">Select Country</option>');

                $.each(res.table[0].rows, function (i) {
                    var c = res.table[0].rows[i].CountryName;
                    var dweb = res.table[0].rows[i].Website;
                    var logo = res.table[0].rows[i].Logo;
                    str.push('<option agent="' + res.table[0].rows[i].AgentOrNot + '" value="' + c + '" distributorweb=" ' + dweb + '"  IsExclusive="' + res.table[0].rows[i].IsExclusive + '"  logo=" ' + logo + '"');
                    if (countrySelected && (countrySelected.toLowerCase() == c.toLowerCase()))
                        str.push(' selected ');
                    str.push('>' + c + '</option>');
                });
                str.push('</select>');
                if (config.row.Class == 'Secondary Antibodies')
                    str.push('</td><td><span id="spSize">100ul</span></td>');
                else if (config.row.Class == 'Fusion protein')
                    str.push('</td><td><span id="spSize">100ug</span></td>');
                else if (config.row.Class == 'Lysates')
                    str.push('</td><td><span id="spSize">100ul</span></td>');
                else
                    str.push('</td><td><span id="spSize">' + config.row.Concentration + 'ug/150ul</span></td>');

                str.push('<td><span id="spPrice">Loading</span></td>');
                str.push('<td><span id="spFreightFee">Loading</span></td>');
                str.push('</tr></tbody></table>');
                str.push('<div id="dvProAddCart" name="' + config.catNo + '" style="padding-right: 5px;" ');

                //set btn bg
                if (config.isFree > 0)
                    str.push('class="addMiniCartFree" title="Test for free.">');
                else
                    str.push('class="addMiniCart" title="Add to cart">');

                str.push('</div>');
                str.push('<div id="dvProNoCountry"/>');

                me.empty().append(str.join(''));

                //Button Event
                if (config.btnShow)
                    $('#dvProAddCart').click(function () { addtoMiniCart(this); });
                else
                    $('#dvProAddCart').remove();
                //Select Event
                $('#country').change(function () { setPriceVal(this); });

                setPriceVal();

            });
        };

        setPriceVal = function (o) {

            var cName = $('#country').val();
            $.cookie('ptg_user_country_selected', $('#country').val(), SYSTEM_CONFIG.CookieOpt);
            if (cName == "") {
                $('#spPrice').text('--');
                $('#spFreightFee').text('--');
                $('#dvProAddCart').hide();
                $('#dvProNoCountry').empty().html('Select a country first to see the price').show();
                return;
            }
            //other
            if (cName.toLowerCase().indexOf("other") >= 0) {
                $('#spPrice').text('--');
                $('#spFreightFee').text('--');
                $('#dvProAddCart').hide();
                $('#dvProNoCountry').empty().html('<a href="../Contacts/Contacts.aspx#US">Please contact our US headquater</a>').show();
                return;
            }

            if ($('#country option:selected').attr('IsExclusive').toLowerCase() == 'true') {

                $('#spPrice').text('--');
                $('#spFreightFee').text('--');
                $('#dvProAddCart').hide();
                var web = $.trim($('#country option:selected').attr('distributorweb'));
                var logo = $.trim($('#country option:selected').attr('logo'));

                var url = ' <span>Please contact our distributor </span> <br /> <a href="http://' + $.trim(web);
                if (cName.toLowerCase() != 'china') url = url + '" ';
                url += '" target="_blank" ><img src="../images/Distributor/' + logo + '" alt="distributor"  title="Please contact our ' + cName + ((cName.toLowerCase() == 'china') ? ' branch' : ' distributor') + '" >' + '</a>';

                $('#dvProNoCountry').empty().html($(url)).show();
                return;
            }

            //Agent
            if ($('#country option:selected').attr('agent').toLowerCase() == 'true') {
                //isFree and japan
                if (config.isFree > 0 && cName == "Japan") {
                    readPrice(cName);
                }
                else {
                    $('#spPrice').text('--');
                    $('#spFreightFee').text('--');
                    $('#dvProAddCart').hide();
                    var url = '<a href="../Contacts/Contacts.aspx';
                    if (cName.toLowerCase() != 'china') url = url + '?step=1';
                    $('#dvProNoCountry').empty().html(url + '#' + cName + '">Please contact our ' + cName + ((cName.toLowerCase() == 'china') ? ' branch' : ' distributor') + '</a>').show();
                }
                return;

            }

   

            //read price
            var index = 0;
            var note = '';
            $.each(exceptionProduct.products, function (i, o) {
                o = $(o);
                var p = $.trim(o[0].productID);
                if (p == config.catNo && o[0].Country == cName) {
                    index++;
                    note = o[0].Note;
                }
            });

            if (index == 0)
                readPrice(cName);
            else {
                $('#spPrice').text('--');
                $('#spFreightFee').text('--');
                $('#dvProAddCart').hide();
                $('#dvProNoCountry').empty().html('<span>' + note + '</span>').show();
            }





        };
        //read price
        readPrice = function (cName) {


            //read price
            $.getJSON("../Handler/ProductHandler.ashx?r=" + Math.random(),
                { func: 'GetProductPrice', param: 'catNo=' + config.catNo + '|cName=' + cName },
                function (res) {

                    if (res.table[1].rows.length > 0) {
                        if (res.table[2].rows.length > 0) {
                            $('#spPrice').html(res.table[0].rows[0].Currency + (parseFloat(res.table[2].rows[0].Price) - parseFloat(res.table[2].rows[0].Discount)).format('#.00'));
                            //$('#spSize').html(res.table[1].rows[0].Size);

                            //is free sample
                            var isFree = false;
                            if (config.isFree > 0 || (res.table.length > 3 && res.table[3].rows[0].isFree > 0)) {
                                $('#spPrice').html('free');
                                isFree = true;
                            }
                            if (config.isFreeCallback) {
                                config.isFreeCallback(isFree);
                            }

                            $('#dvProAddCart').show();
                        }
                        else {//if price error
                            $('#spPrice').html('ERROR');
                            $('#spSize').html('--');
                            $('#dvProAddCart').hide();
                        }

                        $('#spFreightFee').html(res.table[0].rows[0].Currency + parseFloat(res.table[0].rows[0].ShippingFee).format('#.00'));

                        $('#dvProNoCountry').hide();

                        $.cookie('ptg_user_currency_selected', res.table[0].rows[0].Currency, SYSTEM_CONFIG.CookieOpt);

                    }
                    else {
                        if (config.isFreeCallback) {
                            config.isFreeCallback(false);
                        }
                    }

                });
        };

        //insert into mini cart
        addtoMiniCart = function (o) {
            if (checkHasAb()) {
                $.cookie('ptg_user_country_selected', $('#country').val(), SYSTEM_CONFIG.CookieOpt);
                $.MiniCart({ catNo: config.catNo, country: $('#country').val(), dowhat: 'add', from: 'pro', isFree: config.isFree });
            }
        };

        //check ab and second ab
        checkHasAb = function () {
            var rtn = true;
            var abc = new Array();
            var sabc = new Array();
            var rtn = true;
            var cArr = $.cookie('ptg_mini_cart_list');
            if (cArr != null) {
                var itms = eval('[' + cArr + ']');
                $.each(itms, function (i, t) {
                    if (t.t == 1)
                        abc.push(t.catNo);
                    else if (t.t == 2)
                        sabc.push(t);
                });
            }
            if (abc.length == 0) {
                //del from cart
                //for (var i in sabc)
                //    $.MiniCart({ catNo: sabc[i].catNo, dowhat: 'del', incNum: sabc[i].num * -1 });

                if (config.proType == 2) {
                    alert("Must add primary antibody to cart to purchase secondary antibody!"); rtn = false;
                }
            }

            return rtn;
        };

        start = function () {
            init();
            //make();
        };

        start();

    });
}
