﻿
jQuery.fn.ImagesShow = function(config) {

    //参数
    config = jQuery.extend({
        id: null,    //ID
        catNo: null,
        oneWidth: 164,
        showNum: 4,
        data: null,
        dowhat: null,
        findName: null, // which to find
        callback: function() { return false; } //回调函数
    }, config || {});

    return this.each(function() {

        var me = $(this);

        var moveing = false;
        var one_count = 0; //count of show
        var cont_width = null; //div content width
        var clist_width = null; //div list width
        var pageCont = 1;    //page count of show
        var currentPage = 1; //start 1


        moveElement = function(elementID, final_x, final_y, interval) {
            if (!document.getElementById) return false;
            if (!document.getElementById(elementID)) return false;
            var elem = document.getElementById(elementID);
            if (elem.movement) {
                clearTimeout(elem.movement);
            }
            if (!elem.style.left) {
                elem.style.left = "0px";
            }
            if (!elem.style.top) {
                elem.style.top = "0px";
            }
            var xpos = parseInt(elem.style.left);
            var ypos = parseInt(elem.style.top);
            if (xpos == final_x && ypos == final_y) {
                moveing = false;
                return true;
            }
            if (xpos < final_x) {
                var dist = Math.ceil((final_x - xpos) / 10); //Math.ceil求最小的整数，但不小于本身
                xpos = xpos + dist;
            }
            if (xpos > final_x) {
                var dist = Math.ceil((xpos - final_x) / 10);
                xpos = xpos - dist;
            }
            if (ypos < final_y) {
                var dist = Math.ceil((final_y - ypos) / 10);
                ypos = ypos + dist;
            }
            if (ypos > final_y) {
                var dist = Math.ceil((ypos - final_y) / 10);
                ypos = ypos - dist;
            }
            elem.style.left = xpos + "px";
            elem.style.top = ypos + "px";
            var repeat = "moveElement('" + elementID + "'," + final_x + "," + final_y + "," + interval + ")";
            elem.movement = setTimeout(repeat, interval);
        };
        next = function(previousBtn, nextBtn, scrollID, highlightID) {
            if (clist_width <= cont_width) return;
            if (moveing) return;
            moveing = true;
            var vTop = parseInt($('#' + scrollID).css('top'));
            var vLeft = parseInt($('#' + scrollID).css('left'));

            if (vLeft <= (cont_width - clist_width))
                return moveing = false;

            if ((vLeft - cont_width) <= (cont_width - clist_width))
                $('#' + nextBtn).removeClass('next').addClass('last_btn');

            var finalLeft = vLeft - cont_width;
            moveElement(scrollID, finalLeft, vTop, 0.1);
            $('#' + previousBtn).removeClass('first_btn').addClass('previous');

            //set pager
            $('#' + highlightID).children().eq(currentPage - 1).removeClass('current');
            $('#' + highlightID).children().eq(currentPage).addClass('current');
            currentPage++;
        };
        previous = function(previousBtn, nextBtn, scrollID, highlightID) {
            if (moveing) return;
            moveing = true;
            var vTop = parseInt($('#' + scrollID).css("top"));
            var vLeft = parseInt($('#' + scrollID).css("left"));
            if (vLeft >= 0) return moveing = false;
            if (vLeft == -(cont_width)) {
                $('#' + previousBtn).removeClass('previous').addClass('first_btn');
            }
            var finalLeft = vLeft + cont_width;
            moveElement(scrollID, finalLeft, vTop, 0.1);
            $('#' + nextBtn).removeClass('last_btn').addClass('next');

            //set pager
            $('#' + highlightID).children().eq(currentPage - 1).removeClass('current');
            $('#' + highlightID).children().eq(currentPage - 2).addClass('current');
            currentPage--;
        };

        Goto = function(previousBtn, nextBtn, scrollID, highlightID, index) {

            if (moveing) return;
            if (index == currentPage) return;

            moveing = true;
            var vTop = parseInt($('#' + scrollID).css("top"));
            var vLeft = parseInt($('#' + scrollID).css("left"));
            var finalLeft = -cont_width * (index - 1);
            moveElement(scrollID, finalLeft, vTop, 0.1);

            //set pager
            $('#' + highlightID).children().removeClass('current');
            $('#' + highlightID).children().eq(index - 1).addClass('current');

            currentPage = index;

            //prev
            if (index < pageCont)
                $('#' + nextBtn).removeClass('last_btn').addClass('next');
            //next
            if (index > 1)
                $('#' + previousBtn).removeClass('first_btn').addClass('previous');

            if (index == 1) {
                $('#' + previousBtn).removeClass('previous').addClass('first_btn');
            }
            if (index == pageCont) {
                $('#' + nextBtn).removeClass('next').addClass('last_btn');
            }
        };

        init = function() {

            me.addClass('imagesshow');

            if (one_count == 0) {
                me.hide();
                me.prev().hide();
                return;
            }
            cont_width = config.oneWidth * config.showNum; //show 4
            clist_width = $('.v_content_list')[0].offsetWidth;
            pageCont = Math.ceil(clist_width / cont_width);

            if (clist_width <= cont_width) {
                $('#cartoon_previous_btn').addClass("first_btn");
                $('#cartoon_next_btn').addClass("last_btn");
            }
            else {
                $('#cartoon_previous_btn').addClass("first_btn").click(function() { previous('cartoon_previous_btn', 'cartoon_next_btn', 'cartoon_list', 'cartoon_highlight'); });
                $('#cartoon_next_btn').click(function() { next('cartoon_previous_btn', 'cartoon_next_btn', 'cartoon_list', 'cartoon_highlight'); });
            }

            //img mouseover
            $('.v_content_list img').click(function() { showLarge($(this)); });
            $('.v_content_list .thin').parent().click(function() { showLarge($(this)); });

            mPager();
        };

        mAllImg = function() {
            //if has data already
            if (config.catNo == null && config.data != null) {
                fillData(config.data);
                return;
            }

            //WBImage,IFImage,IHCImage
            $.getJSON("../Handler/ProductHandler.ashx?r=" + Math.random(),
            { func: 'GetProMainImages', param: 'catNo=' + config.catNo },
            function(res) {
                var rows = res.table[0].rows;
                fillData(rows);
            });
        };

        fillData = function(rows) {
            var str = new Array();
            str.push('<div class="v_caption  Noprn">');
            str.push('<span class="change_btn"><span id="cartoon_previous_btn" class="first_btn" title="Previous">Prev</span></span>');
            str.push('<span id="cartoon_highlight" class="highlight_tip"></span>');
            str.push('<span class="change_btn"><span id="cartoon_next_btn" class="next" title="Next">Next</span></span>');
            str.push('<span class="last"><a href="javascript:void(0);" class="closethis" title="Close images">Close</a></span>');
            str.push('<span class="last"><a href="PViewDetail.aspx?catNo=' + config.catNo + '" class="extlink" style="margin-right:10px;" >P-VIEW Database</a></span></div>');
            str.push('<div class="v_content">');
            str.push('<div id="cartoon_list" class="v_content_list" style="top:0px; left:0px;">');
            str.push('<ul>');

            $.each(rows, function(i) {
                str.push(mOneImg(rows[i]));
            });
            str.push('</ul></div></div>');

            me.empty().append(str.join(''));

            $(".v_content_list").css("width", config.oneWidth * one_count);

            if (one_count > 0 && one_count <= 2)
                $(".v_content_list").css("left", config.oneWidth);

            if (config.inSearch) {

                $('.closethis').show().click(function() { config.showObj.next().replaceWith(''); adjustMain(); });
                config.showObj.after(me.parent().parent());
                if (one_count > 0) {
                    config.showObj.next().show();
                }
            }
            me.show();
            adjustMain();

            init();

            if (config.inSearch) {
                $('.v_content').css("width", '100%').css('border', '0px'); ;
            }
        };

        mOneImg = function(g) {
            if (!g.n) return;
            var str = new Array();
            str.push('<li><a href="javascript:void(0);" src="' + getPath(g) + '">');
            str.push('<img src="' + getPath(g) + '" alt="' + g.n + '"');
            if (g.t == "1") str.push(" class='thin'");
            str.push('/>');
            str.push('</a>');
            str.push('<span>' + g.dsp + '</span></li>');
            one_count++;
            return str.join("");
        };

        mPager = function() {
            var str = new Array();
            for (var i = 1; i <= pageCont; i++) {
                if (i == currentPage) str.push('<a class="current">' + i + '</a>');
                else
                    str.push('<a>' + i + '</a>');
            }
            $('.highlight_tip').empty().append(str.join(''));

            $('.highlight_tip a').click(function() { Goto('cartoon_previous_btn', 'cartoon_next_btn', 'cartoon_list', 'cartoon_highlight', $(this).text()); });
        }

        getPath = function(g) {
            if (g.t == "1") return 'Pictures/WBImages/' + g.n;
            else if (g.t == "2") return 'Pictures/IHCImages/' + g.n;
            else if (g.t == "3") return 'Pictures/IFImages/' + g.n;
            else if (g.t == "4") return 'Pictures/AdditionalImages/' + g.n;
            else return g.n;
        };

        showLarge = function(obj) {
            if ($('#enlarge_images').length == 0) {
                me.append('<div id="enlarge_images" class="showlarge"/> ');
                var lf = (SYSTEM_CONFIG.CliWidth - 400) / 2;
                var tp = (SYSTEM_CONFIG.CliHeight - 300) / 2;
                $('#enlarge_images').css('left', lf).css('top', tp);
                //$(document).click(function() { $('#enlarge_images').fadeOut(); });
            }

            var tp = (SYSTEM_CONFIG.CliHeight - 300) / 2 + document.documentElement.scrollTop;

            $('#enlarge_images').empty().css({ top: tp, bgcolor: '#fff', cursor: 'move' })
            .append('<a class="close"/><img src="' + obj.attr('src') + '"  height="400" />')
            .jqDrag()
            .fadeIn();

            $('#enlarge_images .close').click(function() { $(this).parent().fadeOut(); });
        };

        find = function() {
            if (config.findName == null) return;
            //find index
            var index = $("#cartoon_list li").index($('#cartoon_list li img[alt="' + config.findName + '"]').parent().parent()[0]);
            var b = $("#cartoon_list li:eq(" + index + ")");

            //$("#cartoon_list li").removeClass('highlight');
            $("#cartoon_list li:eq(" + index + ")").addClass('highlight');

        };

        start = function() {
            mAllImg();
        };


        switch (config.dowhat) {
            case 'find':
                find();
                break;

            default:
                start();
                break;
        }


    });
}


