﻿;
(
        function($) {
            $.fn.SSPlay = function(options) {
                var me = this;
                var defaults = { url: null, showThumbs: false, container: null, width: null, height: null, setting: { play: { speed: 3000, fadeSpeed: 1500 }, css: {}, barCSS: {}} };

                $.extend(defaults, options);
                if (defaults.width > 608) {
                    defaults.width = 608;
                }
                if (defaults.showThumbs) {
                    defaults.height = 342;
                }
                else {
                    if (defaults.width > 600) {
                        defaults.height = 342;
                    }
                    else {
                        defaults.height = 258;
                    }
                }
                var hostWeb = document.location.href.replace("http://", "").split("/")[0];
                var myUrl = defaults.url.replace("http://", "").split("/");
                myUrl[0] = hostWeb;
                var url = "http://" + myUrl.join("/");
                defaults.url = url;
                this.playTimeOut = null;
                this.component = { cImg: null, tbar: null, cIcon: null, pgInfo: null, isPgShow: false };
                this.playIndex = 0;
                this.galleryData = [];
                this.galleryTypeData = [];
                this.stopped = false;
                this.playDirection = "next";
                this.table = null;
                this.R = null;
                this.L = null;
                this.isMouseUp = false;
                this.currentItem = null;
                this.highLighter = null;
                this.isScroll = false;
                this.addLoader = function(container) {
                    var div = $("<div class=\"Loading\">");
                    div.appendTo(container);
                    return div;
                };
                this.loadData = function(json, loaded) {
                    if (loaded) {

                        if (json && json.gallery) {
                            if (json.gallery.images) {
                                if (json.gallery.images.image.length) {
                                    me.galleryData = json.gallery.images.image;
                                }
                                else {
                                    me.galleryData = new Array();
                                    me.galleryData.push(json.gallery.images.image);
                                }
                                for (var i = 0; i < me.galleryData.length; i++) {
                                    me.galleryData[i].galleryType = json.gallery;
                                }
                                me.galleryTypeData = json.gallery;
                            }
                            else {
                                me.galleryData = new Array();
                                me.galleryTypeData = json.gallery;
                                var i;
                                for (i = 0; i < json.gallery.length; i++) {
                                    var j;
                                    var g = json.gallery[i];
                                    if (g.images.image.length) {
                                        for (j = 0; j < g.images.image.length; j++) {
                                            var image = g.images.image[j];
                                            image.galleryType = g;
                                            me.galleryData.push(image);
                                        }
                                    }
                                    else {
                                        var image = g.images.image;
                                        image.galleryType = g;
                                        me.galleryData.push(image);
                                    }
                                }
                            }
                            for (var i = 0; i < me.galleryData.length; i++) {
                                var item = me.galleryData[i];
                                var temp = item.url;
                                item.url = temp.replace("images/Gallery/", "xml/GetImage.aspx?n=") + "&t=g&w=" + defaults.width + "&h=" + defaults.height;
                                item.oldUrl = temp;
                            }
                            me.install();
                            me.play();
                        }
                        else {
                            //alert("Error of loading gallery data");
                        }
                    }
                    else {
                        var loader = this.addLoader(defaults.container);
                        $.ajax(
                        { dataType: 'text',
                            cache: false, url: defaults.url, error: function(x) { alert(x.reponseText); loader.remove(); },
                            success: function(data) {

                                loader.remove();
                                var xmlData = xml2json.parser(data)

                                me.loadData(xmlData.imagegallery, true);
                            }
                        });
                    }
                };
                this.toogleStop = function(isStop) {
                    clearTimeout(me.playTimeOut);
                    me.stopped = isStop;
                };
                this.resize = function(src, mw, mh) {
                    var img = new Image();
                    img.src = src.attr('src');
                    var meW = img.width;
                    var meH = img.height;
                    var newWidth = {};
                    if (meW > meH && meW > mw) {
                        newWidth.w = mw;
                        newWidth.h = mw / meW * meH;
                    }
                    else if (meH > meW) {
                        newWidth.h = mh;
                        newWidth.w = mh / meH * meW;
                    }
                    else {
                        newWidth.w = meW;
                        newWidth.h = meH;
                    }
                    src.css({ width: newWidth.w, height: newWidth.h });
                    return newWidth;
                };
                this.previous = function() {
                    me.playIndex--;
                    if (me.playIndex < 0) { me.playIndex = me.galleryData.length - 1; };
                    me.play();
                };
                this.next = function() {
                    me.playIndex++;
                    if (me.playIndex > (me.galleryData.length - 1)) { me.playIndex = 0; };
                    me.play();
                };
                this.play = function() {
                    var img = null;
                    var removeOldOne = function() {
                        if (me.component.cImg != null) {
                            //me.component.cImg.fadeTo(1000, 0, function () { me.component.cImg.remove(); me.component.cImg = img; });
                            me.component.cImg.remove(); me.component.cImg = img;

                        }
                        else {
                            me.component.cImg = img;
                        }
                    };

                    var showImage = function() {

                        var item = me.galleryData[me.playIndex];

                        if (item && item.error == undefined) {
                            img = $("<img src=\"" + defaults.imageUrl(item) + "\"/>");

                            img.css({ "max-Width": defaults.width, "max-Height": defaults.height, position: 'absolute', top: 0, right: 0, opacity: 0 });
                            var loader = me.addLoader(defaults.container);
                            img.load(function() {
                                if (defaults.showThumbs) {
                                    me.hightLightGalleryType(item, true);
                                }
                                me.currentItem = item;
                                if (item.title && item.title.length > 0) {
                                    me.component.titleDiv.html(item.title);
                                }
                                else if (item.galleryType && item.galleryType.title) {
                                    me.component.titleDiv.html(item.galleryType.title);
                                }
                                else {
                                    me.component.titleDiv.html("");
                                }
                                if (item.photographer && item.photographer.length > 0) {
                                    if (!me.component.isPgShow) {
                                        me.component.cIcon.show();
                                    }
                                    me.component.pgInfo.html(item.photographer);
                                }
                                else {
                                    me.component.pgInfo.html("").hide().css({ width: 1, right: 0 });
                                    me.component.cIcon.hide();
                                    me.component.isPgShow = false;
                                    me.component.titleDiv.show();
                                }
                                loader.remove();
                                if (item.linkurl && item.linkurl.length > 4) {
                                    img.css({ cursor: 'pointer' });
                                    var a = $("<a href=\"" + item.linkurl + "\" target=\"" + item.linkurltype + "\"></a>");
                                    img.appendTo(a);
                                    a.appendTo(defaults.container);
                                }
                                else {
                                    img.appendTo(defaults.container);
                                }
                                //var newSize = me.resize(img, defaults.width, defaults.height);
                                //$(defaults.container).css({ height: newSize.h });
                                img.fadeTo(defaults.setting.play.fadeSpeed, 1, function() {
                                    removeOldOne();
                                    if (me.playTimeOut != null) {
                                        clearTimeout(me.playTimeOut);
                                    }
                                    if (!me.stopped) {
                                        if (me.playDirection == "next") {
                                            me.playTimeOut = setTimeout(function() { me.next() }, defaults.setting.play.speed);
                                        }
                                        else {
                                            me.playTimeOut = setTimeout(function() { me.previous(); }, defaults.setting.play.speed);
                                        }
                                    }
                                });
                            });
                            img.error(function() { loader.remove(); img.remove(); item.error = true; me.next(); });
                        }
                    }

                    showImage();

                };
                this.playGallery = function(item) {
                    var i;
                    for (i = 0; i < me.galleryData.length; i++) {
                        var g = me.galleryData[i];
                        if (g.galleryType.id == item.id) {
                            this.playIndex = i;
                            break;
                        }
                    }
                    this.play();
                };

                this.hightLightGalleryType = function(item, isAnimated) {
                    var needToogle = true;
                    if (me.currentItem != null && me.currentItem.galleryType.id == item.galleryType.id) {
                        needToogle = false;
                    }
                    var ui = item.galleryType.ui;
                    var div = null;
                    if (me.highLighter == null) {
                        div = $("<div class=\"hightlighted\">");
                        div.css({ position: 'absolute' });
                        //div.appendTo($("#divProductContainer"));
                        me.highLighter = div;
                    }
                    else {
                        div = me.highLighter;
                    }

                    var left = ui.td.position().left + me.table.position().left;
                    var toogle = function(parent) {
                        if (parent.attr("id") == "divProductContainer") {
                            div.css({ top: 0, left: 0 });
                            div.hide().detach().appendTo(parent).fadeIn('fast');
                            //div.detach().appendTo(parent).show();
                            //div.animate({ left: ui.td.position().left }, function() { div.detach().appendTo(ui.div); div.css({ top: 0, left: 0 }); });
                        }
                        else {

                            div.fadeOut('fast', function(e) {
                                if ($.browser.msie) {
                                    div.hide().detach().appendTo(parent).css({ top: 0, left: 0, width: '100%', height: '100%' }).fadeIn('fast');
                                }
                                else {
                                    div.hide().detach().appendTo(parent).css({ top: 0, left: 0 }).fadeIn('fast');
                                }
                            });

                        }
                    }
                    if (me.isScroll) {
                        toogle(ui.div);
                        return;
                    }
                    var index = me.table.position().left / 63 + ui.td[0].cellIndex;
                    var left = ui.td.position().left + me.table.position().left;
                    me.table.clearQueue();
                    if (parseInt(ui.td[0].cellIndex) > 8) {
                        if (needToogle) {
                            toogle(ui.div);
                        }
                        me.table.animate({ left: -(63 * (ui.td[0].cellIndex - 8)) });
                    }
                    else if (parseInt(ui.td[0].cellIndex) < 9) {
                        if (needToogle) {
                            toogle(ui.div);
                        }
                        me.table.animate({ left: 0 });

                    }
                    else {

                    }


                };
                this.createGalleryTypeBar = function() {
                    var div = $("<div>");
                    div.css({ width: defaults.width }).attr({ 'class': 'GPThumbbar' });
                    var table = $('<table class="GPScroller" cellpadding="0" border="0" width="100%" cellspacing="0"><tr><td valign="middle"><div class="scrollLeft_On" ></div></td><td align="center"><div id="divProductContainer"  style="width:567px; height:61px; position:relative; overflow:hidden;"></div></td><td valign="middle"><div class="scrollRight_On" ></div></td></tr></table>');
                    table.appendTo(div);
                    div.appendTo(defaults.container.parent());
                    if (this.table == null) {
                        this.table = $("<table border='0'  cellpadding='0' cellspacing='0' style='position:absolute; top:0px;left:0px;'><tr></tr></table>");
                    }
                    var tr = this.table.find("tr");

                    me.R = $(".scrollRight_On");
                    me.L = $(".scrollLeft_On");

                    $(me.galleryTypeData).each(
                        function(index, item) {
                            var td = $("<td  align='center' valign='top'><div class='container'><table style='height:61px;'  cellpadding='0' cellspacing='0'><tr><td class='imgContainer' valign='middle'></td></tr></table></div></td>");
                            var div = td.find(".imgContainer");
                            var url = item.thumburl;


                            var img = $("<img style='background-color:#FFFFFF; max-height:61px;' src=\"" + url + "\"/>");
                            item.ui = { td: td, selected: false, div: td.find(".container"), img: img };
                            item.loader = me.addLoader(div);
                            item.ui.div.mousedown(function(e) { me.playGallery(item); });
                            img.load(function(e) { item.loader.remove(); delete item.loader; img.appendTo(div); });
                            img.error(function(e) { item.loader.remove(); delete item.loader; });
                            td.appendTo(tr);
                            for (var i = 0; i < me.galleryData.length; i++) {
                                if (me.galleryData[i].galleryType.id == item.id) {
                                    me.galleryData[i].galleryType = item;
                                    break;
                                }
                            }
                        }
                    );
                    var interval = null;
                    this.table.appendTo($("#divProductContainer"));
                    if (me.galleryTypeData.length > 9) {
                        me.R.mouseover(function(e) { me.R.clearQueue(); me.R.fadeTo("fast", 0.5); }).mouseout(function(e) { me.R.clearQueue(); me.R.fadeTo("fast", 1); });
                        me.L.mouseover(function(e) { me.L.clearQueue(); me.L.fadeTo("fast", 0.5); }).mouseout(function(e) { me.L.clearQueue(); me.L.fadeTo("fast", 1); });
                        me.R.mousedown(function(e) { me.isMouseUp = false; clearInterval(interval); me.table.clearQueue(); interval = setInterval(function() { me.doScroll('R'); }, 20) });
                        me.L.mousedown(function(e) { me.isMouseUp = false; clearInterval(interval); me.table.clearQueue(); interval = setInterval(function() { me.doScroll('L'); }, 20) });
                        me.R.mouseup(function(e) { me.isMouseUp = true; clearInterval(interval); me.stopScroll('R'); });
                        me.L.mouseup(function(e) { me.isMouseUp = true; clearInterval(interval); me.stopScroll('L'); });
                    }
                    else {
                        me.R.fadeTo('fast', 0.2);
                        me.L.fadeTo('fast', 0.2);
                    }
                };
                this.stopScroll = function(direction) {
                    var left = me.table.position().left;
                    var margin = left % 63;
                    var end = function() {
                        var eleft = me.table.position().left;
                        var eMargin = eleft % 63;
                        me.isScroll = false;
                    }

                    if (Math.abs(margin) > 0) {
                        var snapLeft = left;
                        if (direction == 'R') {
                            snapLeft = left - (63 - Math.abs(margin));
                            if ((Math.abs(snapLeft) + $("#divProductContainer").width()) > me.table.width()) {
                                snapLeft = -(me.table.width() - $("#divProductContainer").width());
                            }
                            me.table.clearQueue();
                            me.table.animate({ left: snapLeft }, function(e) { end(); });
                        }
                        else {
                            snapLeft = left - margin;
                            me.table.clearQueue();
                            me.table.animate({ left: snapLeft }, function(e) { end(); });
                        }
                    }
                    else {
                        me.isScroll = false;
                    }
                };
                this.doScroll = function(direction) {
                    me.isScroll = true;
                    var div = $("#divProductContainer");
                    if (direction == 'R') {
                        if (me.table.width() + me.table.position().left > div.width()) {
                            me.table.css({ left: me.table.position().left - 5 });
                        }
                    }
                    else {
                        if (me.table.position().left < 0) {
                            me.table.css({ left: me.table.position().left + 5 });
                        }
                    }

                };
                this.createThumbnailBar = function() {
                    var width = defaults.width - defaults.setting.controlBarCSS.width;
                    var div = $("<div>");
                    div.css(defaults.setting.barCSS).css({ position: "absolute", 'z-Index': 9999, width: '100%', background: 'none', opacity: 1 }).appendTo(defaults.container);
                    var table = $("<table  cellpadding='0' cellspacing='0' border='0'><tr><td style='width:" + width + "px;'><div style='height:30px;position:relative'><div id=\"divGalleryTitleContainer\"></div></div></td><td><div style='height:30px;width:" + defaults.setting.controlBarCSS.width + "px; position:relative'><div id=\"divGalleryControlBg\"></div></div></td></tr></table>");


                    table.css({ width: '100%' });
                    me.component.titleBgDiv = table.find("#divGalleryTitleContainer");
                    me.component.controlDiv = table.find("#divGalleryControlBg");
                    var c = me.component;
                    c.controlDiv.css(defaults.setting.controlBarCSS).css({ position: 'absolute', top: 0, left: 0 });
                    c.titleBgDiv.css(defaults.setting.titleBar).css({ width: width, position: 'absolute', top: 0, left: 0, overflow: 'hidden' });

                    table.appendTo(div);

                    me.component.tbar = div;
                    c.controlDiv.parent().css({ width: defaults.setting.controlBarCSS.width });

                    var playControl = $("<table class='GPControl' border='0' width='100'><tr><td><div class='prev'></div></td><td align=\"center\"><div class='pause'></div></td><td><div class='next'></div></td></tr></table>");
                    playControl.appendTo(c.controlDiv.parent()).css({ height: '100%', position: 'absolute', top: 0, left: 0 });
                    var titleBar = $("<div class=\"GPTitleInfo\">").css({ position: 'absolute', 'z-Index': 9999, width: 'auto', height: '100%', top: 0, left: 0 });
                    titleBar.appendTo(c.titleBgDiv.parent());
                    me.component.titleDiv = titleBar;


                    var isMoveing = false;
                    var pg = $("<div>").css({ cursor: 'default', color: "#FFFFFF", position: 'absolute', top: 5, right: 0, opacity: 0, height: 15, width: 1, overflow: 'hidden' });
                    pg.appendTo(c.titleBgDiv.parent()).html("ssssssssssssss");
                    var fun = function(e) {
                        if (isMoveing) { return; }
                        //document.title = "leave";
                        pg.clearQueue();
                        isMoveing = true;
                        pg.animate({ opacity: 0, width: 1, right: 0 }, 100,
                        function() {
                            pg.unbind("mouseleave", fun);
                            isMoveing = false;
                            cIcon.show();
                            c.titleDiv.show();
                            c.isPgShow = false;
                        });
                    }
                    var hideInfo = function() {
                        isMoveing = false;
                        c.isPgShow = true;

                    }
                    var showPg = function() {
                        //document.title = "Enter";
                        pg.clearQueue();
                        isMoveing = true;
                        pg.unbind("mouseleave", fun);
                        pg.bind("mouseleave", fun);
                        c.titleDiv.hide();
                        var t = $("<div style=\"position:absolute; width:auto; top:-200px; left:0px;\">");
                        t.html(pg.html());
                        t.appendTo(document.body);
                        var w = t.width();
                        t.remove();

                        pg.animate({ opacity: 1, width: w + 10, right: 0 }, 100, hideInfo);
                    }
                    var cIcon = $("<div class=\"GPCameraIcon\">");
                    cIcon.appendTo(c.titleBgDiv.parent());
                    cIcon.mouseenter(function() {
                        cIcon.hide();
                        showPg();
                    });
                    me.component.cIcon = cIcon;
                    me.component.pgInfo = pg;
                    var nextBtn = playControl.find(".next");
                    var pauseBtn = playControl.find(".pause");
                    var prevBtn = playControl.find(".prev");

                    nextBtn.mouseover(function(e) { nextBtn.attr({ 'class': 'next_Over' }); }).mouseout(function(e) { nextBtn.attr({ 'class': 'next' }); });
                    pauseBtn.mouseover(function(e) { pauseBtn.attr({ 'class': 'pause_Over' }); }).mouseout(function(e) { pauseBtn.attr({ 'class': 'pause' }); });
                    prevBtn.mouseover(function(e) { prevBtn.attr({ 'class': 'prev_Over' }); }).mouseout(function(e) { prevBtn.attr({ 'class': 'prev' }); });
                    pauseBtn.parent().css({ width: 20 });
                    nextBtn.mousedown(function(e) { nextBtn.clearQueue(); me.toogleStop(false); me.playDirection = "next"; me.next(); pauseBtn.show(); });
                    prevBtn.mousedown(function(e) { prevBtn.clearQueue(); me.toogleStop(false); me.playDirection = "prev"; me.previous(); pauseBtn.show(); });
                    pauseBtn.mousedown(function(e) { pauseBtn.clearQueue(); me.toogleStop(true); pauseBtn.hide(); });
                    if (me.galleryData.length < 2) {
                        playControl.hide();
                    }

                };
                this.install = function() {

                    if (defaults.setting && defaults.setting.css) { $(defaults.container).css(defaults.setting.css); };
                    if (defaults.setting && defaults.setting.barCSS) {
                        me.createThumbnailBar();
                    }
                    $(defaults.container).css({ position: "relative", height: defaults.height, width: defaults.width });
                    if (defaults.showThumbs) {
                        me.createGalleryTypeBar();
                    }
                };
                this.loadData(null, false);
                return me;
            }
        }

)(jQuery);
