/*
 * jQuery Shink plugin
 *
 * Version 1.1  
 * Create Date : (03/15/2009)
 * Modify Date : (03/24/2009)
 * @requires : jQuery v1.3.1
 * @Author : L.Rain
 * @Channel : zhuanji
 * Copyright : Openv. All rights reserved.
 */ 
(function($) {
    $.fn.fixPNG = function() {
        return this.each(function() {
            var image = $(this).css('backgroundImage');
            if (image.match(/^url\(["']?(.*\.png)["']?\)$/i)) {
                image = RegExp.$1;
                $(this).css({
                    'backgroundImage': 'none',
                    'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=" + ($(this).css('backgroundRepeat') == 'no-repeat' ? 'crop': 'scale') + ", src='" + image + "')"
                }).each(function() {
                    var position = $(this).css('position');
                    if (position != 'absolute' && position != 'relative')
                        $(this).css('position', 'relative');
                });
            }
        })
        };
    var elem, opts, loadingTimer, href, shrinkType, flashHtml, loadingPostion = 1, busy = false, imagePreloader = new Image, imageRegExp = /\.(jpg|gif|png|bmp|jpeg)(.*)?$/i , flashRegExp = /#flashPlay/i;
    $.fn.extend({
        shrink: function(settings) {
            var matchedGroup = this;

            settings = $.extend({}, $.shrink.defaults, settings);

            var initialize = function() {
                elem = this;
                opts = settings;
                start();
                return false;
            };
            var start = function() {
                if (busy) return;
                
                opts.itemArray = [];
                opts.itemCurrent = 0;
                var item = {};

                if (!elem.rel || elem.rel == '') {
                    item = {
                        title: elem.title,
                        href: elem.href
                    };
                    if ($(elem).children('img:first').length) {
                        item.orgi = $(elem).children('img:first')[0];
                    }
                    opts.itemArray.push(item);
                } else {
                    var Groups = matchedGroup.filter('a[rel=' + elem.rel + ']'),
                    member = {};
                    for (var i = 0; i < Groups.length; i++) {
                        member = Groups[i];
                        item = {
                            title: member.title,
                            href: member.href
                        };
                        if ($(member).children('img:first').length) {
                            item.orgi = $(member).children('img:first')[0];
                        }
                        opts.itemArray.push(item);
                    }
                    while (opts.itemArray[opts.itemCurrent].href != elem.href) {
                        opts.itemCurrent++;
                    }
                }
                if (opts.showHideLayer) {
                    if (YU.is_Ie) {
                        //$('embed, object, select').css('visibility', 'hidden');
                    }
                    $.shrink.impl.createHideLayer();
                }

                href = opts.itemArray[opts.itemCurrent].href;
                if (href.match(imageRegExp)) {
                    shrinkType = "img";
                } else if (href.match(flashRegExp)) {
                    shrinkType = "flash";
                    var reg = /#flashPlay(\d*?)$/i;
                    opts.nowPlayNum = elem.href.match(reg)[1];
                } else {
                    shrinkType = "ajax";
                }
                setItem();
            };
            var setItem = function() {

                $("#shrink_right, #shrink_left, #shrink_close").hide();

                if (shrinkType == 'img') {
                    imagePreloader = new Image();
                    imagePreloader.src = href;
                    if (imagePreloader.complete) {
                        proceedImage();
                    } else {
                        $.shrink.impl.showLoading();
                        $(imagePreloader).unbind().bind('load', function() {
                            $("#shrink_loading").hide();
                            proceedImage();
                        });
                    }
                } else if (shrinkType == 'flash') {
                    proceedFlash();
                } else {
                    $.shrink.impl.showLoading();
                    $.ajax({
                        type: opts.ajaxType,
                        url: href,
                        success: function(data) {
                            $("#shrink_loading").hide();
                            setContent(data, opts.width, opts.height);
                        }
                    });
                }
            };
            var proceedImage = function() {
                var width = imagePreloader.width;
                var height = imagePreloader.height;
                setContent('<img class="shrink_img" id="shrink_img" src="' + href + '" />', width, height);
            };
            var neighborImage = function() {
                if (opts.itemCurrent != 0) {
                    $("#shrink_left").unbind('click').click(function(e) {
                        e.stopPropagation();
                        opts.itemCurrent--;
                        opts.nowPlayNum--;
                        setItem();
                        return false;
                    });
                    $("#shrink_left").show();
                }
                if (opts.itemArray[opts.itemCurrent + 1]) {
                    $("#shrink_right").unbind('click').click(function(e) {
                        e.stopPropagation();
                        opts.itemCurrent++;
                        opts.nowPlayNum++;
                        setItem();
                        return false;
                    });
                    $("#shrink_right").show();
                }
            };
            var proceedFlash = function() {
                var tmp = {};
                if (opts.isrecommend) {
                    $(".live").remove();
                    $(opts.itemArray[opts.itemCurrent].orgi).parent().parent().parent().children(".recommend-font").append("<div class=\"live\">正在播放</div>");
                    tmp = T[opts.nowPlayNum];
                } else {
                    tmp = v[opts.nowPlayNum];
                }
                var swf_path = 'http://img.openv.tv/hd/swf/hd_player.swf';
                var _qval = 'tv=0';
                if (tmp.ishd == 1) {
                    _qval += ',hd=1';
                }
                _qval += ',ref=' + encodeURIComponent(document.referrer) + ',channel=' + encodeURIComponent(location.href);
                var sFV = '&hasLeftBar=false';
                sFV += '&pid=' + tmp.ref + '&playNowTitle=' + encodeURIComponent(tmp.title) + '&q=' + _qval + '&autostart=true&showOverEvent=1&culatePlayerTimer=true&playADstatu=true&showLRmenu=false';
                setContent('<embed width="' + opts.flashWidth + '" height="' + opts.flashHeight + '" wmode="transparent" quality="high" allowfullscreen="true"  allowscriptaccess="always" type="application/x-shockwave-flash" src="' + swf_path + '?' + sFV + '" />', opts.flashWidth, opts.flashHeight);
            };
            var setContent = function(value, width, height) {

                busy = true;

                if (YU.is_Ie) {
                    $("#shrink_content")[0].style.removeExpression('height');
                    $("#shrink_content")[0].style.removeExpression('width');
                }

                var pad = opts.padding;
                if (pad > 0) {
                    $("#shrink_content").css({
                        top: pad + 'px',
                        right: pad + 'px',
                        bottom: pad + 'px',
                        left: pad + 'px',
                        width: 'auto',
                        height: 'auto'
                    });
                    width += pad * 2;
                    height += pad * 2;

                    if (YU.is_Ie) {
                        $("#shrink_content")[0].style.setExpression('height', '(this.parentNode.clientHeight - 20)');
                        $("#shrink_content")[0].style.setExpression('width', '(this.parentNode.clientWidth - 20)');
                    }
                } else {
                    $("#shrink_content").css({
                        top: 0,
                        right: 0,
                        bottom: 0,
                        left: 0,
                        width: '100%',
                        height: '100%'
                    });
                }

                var pageParam = YU.getCenterPx({
                    _width: width,
                    _height: height
                });
                var itemOpts = {
                    width: width + 'px',
                    height: height + 'px',
                    left: pageParam.width + 'px',
                    top: pageParam.height + 'px'
                };

                if ($('#shrink_outer').is(":visible") && width == $("#shrink_outer").width() && height == $("#shrink_outer").height()) {
                    $('#shrink_content').fadeOut('slow', function() {
                        $('.shrink_inner', '#shrink').css({
                            backgroundColor: opts.backgroundColor
                        });
                        $("#shrink_content").empty().html(value).fadeIn("normal", function() {
                            finish();
                        });
                    });
                    return;
                }
                if ($('#shrink_outer').is(":visible")) {
                    $('#shrink_content').fadeOut('slow', function() {
                        $('#shrink_outer').animate(itemOpts, 500, function() {
                            $('.shrink_inner', '#shrink').css({
                                backgroundColor: opts.backgroundColor
                            });
                            $("#shrink_content").empty().html(value).fadeIn("normal", function() {
                                finish();
                            });
                        });
                    });
                    return;
                } else {
                    itemOpts.opacity = 'show';
                    var imgObj = opts.itemArray[opts.itemCurrent].orgi;
                    var b = YU.fetchOffset(imgObj);

                    $("#shrink_outer").css({
                        "width": (imgObj.offsetWidth) + 'px',
                        "height": (imgObj.offsetHeight) + 'px',
                        "left": (b.left - 18) + 'px',
                        "top": (b.top - 18) + 'px'
                    });

                    $('.shrink_inner', '#shrink').css({
                        backgroundColor: opts.backgroundColor
                    });

                    if (shrinkType != 'img') {
                        $("#shrink_content", "#shrink_outer").empty();
                        $("#shrink_outer").animate(itemOpts, 500, function() {
                            finish(value);
                        })
                        } else {
                        $("#shrink_content", "#shrink_outer").empty().html(value);
                        $("#shrink_outer").animate(itemOpts, 500, function() {
                            finish();
                        })
                        }
                }
            };
            var finish = function(value) {
                if (shrinkType != 'ajax' && opts.itemArray.length > 1) {
                    neighborImage();
                }
                if (value) $("#shrink_content", "#shrink_outer").html(value);
                if (opts.itemArray[opts.itemCurrent].title != '') {
                    $('#shrink_title').html('<table cellspacing="0" cellpadding="0" border="0">\
                                                  <tbody>\
                                                      <tr>\
                                                          <td class="shrink_title_bg" id="shrink_title_left"/>\
                                                          <td class="shrink_title_bg" id="shrink_title_main">\
                                                               正在播放:' + opts.itemArray[opts.itemCurrent].title + '\
                                                          </td>\
                                                          <td class="shrink_title_bg" id="shrink_title_right"/>\
                                                      </tr>\
                                                 </tbody>\
                                             </table>').show();
                    if (YU.is_Ie) {
                        $(".shrink_title_bg").fixPNG();
                    }
                }
                $("#shrink_close").show().click($.shrink.impl.close);

                $.shrink.impl.setDrag($(".shrink_bg_n")[0], "shrink_outer");

                $(document).keydown(function(event) {
                    event = event || window.event;
                    if (event.keyCode == 27) {
                        $.shrink.impl.close();
                        $(document).unbind("keydown");
                    } else if (opts.itemArray[opts.itemCurrent + 1] && event.keyCode == 39) {
                        opts.itemCurrent++;
                        opts.nowPlayNum++;
                        setItem();
                        $(document).unbind('keydown');
                    } else if (opts.itemCurrent != 0 && event.keyCode == 37) {
                        opts.itemCurrent--;
                        opts.nowPlayNum--;
                        setItem();
                        $(document).unbind('keydown');
                    }
                });
                busy = false;
            };
            return this.unbind('click').click(initialize);
        }
    });
    $.shrink = {};
    $.shrink.version = '1.1';
    $.shrink.defaults = {
        padding: 10,
        hidelayerOpacity: 0.6,
        showHideLayer: false,
        isrecommend: false,
        backgroundColor: '#FFF',
        width: 400,
        height: 400,
        ajaxType: 'post',
        flashWidth: 588,
        flashHeight: 456
    };
    var userAgent = navigator.userAgent.toLowerCase();
    var YU = $.shrink.impl = {
        is_Ie: (userAgent.indexOf('msie') != -1) && userAgent.substr(userAgent.indexOf('msie') + 5, 3),
        is_Ie6: jQuery.browser.msie && /msie 6.0/.test(userAgent),
        zIndex: 100,
        build: function() {
            var shrinkElem = $("#shrink");
            this.createHideLayer();
            if (!shrinkElem.length) {
                shrinkElem = $('<div id="shrink">\
                                   <div class="shrink_loading blockLY" id="shrink_loading">\
                                          <div></div>\
                                   </div>\
                                   <div class="shrink_outer blockLY" id="shrink_outer">\
                                     <div class="shrink_inner">\
                                       <div class="shrink_close" id="shrink_close"></div>\
                                       <a href="#" hidefocus="true" id="shrink_left"><span id="shrink_left_span" title="上一个"/></a>\
                                       <a href="#" hidefocus="true" id="shrink_right"><span id="shrink_right_span" title="下一个" /></a>\
                                       <div class="shrink_border">\
                                        	  <div class="shrink_bg shrink_bg_n"><em>点击可拖拽</em></div>\
                                        	  <div class="shrink_bg shrink_bg_w"></div>\
                                            <div class="shrink_bg shrink_bg_e"></div>\
                                            <div class="shrink_bg shrink_bg_s"></div>\
                                            <div class="shrink_bg shrink_bg_nw"></div>\
                                            <div class="shrink_bg shrink_bg_ne"></div>\
                                            <div class="shrink_bg shrink_bg_se"></div>\
                                            <div class="shrink_bg shrink_bg_sw"></div>\
                                       </div>\
                                       <div class="shrink_content" id="shrink_content"></div>\
                                       <div class="shrink_title" id="shrink_title">\
                                       </div>\
                                     </div>\
                                   </div>\
                                </div>');
                shrinkElem.appendTo("body");
                if (YU.is_Ie) {
                    $("#shrink_close , #shrink_left_span ,#shrink_right_span , .shrink_bg , .shrink_loading ").fixPNG();
                }
            }
        },
        showLoading: function() {
            if (loadingTimer) clearInterval(loadingTimer);
            var page = this.getCenterPx({
                _width: 40,
                _height: 40
            });
            $("#shrink_loading").css({
                left: page.width + "px",
                top: page.height + "px"
            }).show();
            loadingTimer = setInterval(this.animateLoading, 50);
        },
        animateLoading: function() {
            if (!$("#shrink_loading").is(':visible')) {
                clearInterval(loadingTimer);
                return;
            }

            $("#shrink_loading").children("div").css({
                top: (loadingPostion * -40) + "px"
            });
            loadingPostion = (loadingPostion + 1) % 12;
        },
        close: function() {
            $("#shrink_close, #shrink_loading, #shrink_left, #shrink_right , #shrink_title").hide();
            $(document).unbind('keydown');
            var imgObj = opts.itemArray[opts.itemCurrent].orgi;
            var b = YU.fetchOffset(imgObj);
            var itemOpts = {
                width: imgObj.offsetWidth + 'px',
                height: imgObj.offsetHeight + 'px',
                left: (b.left - 18) + 'px',
                top: (b.top - 18) + 'px',
                opacity: 'hide'
            };
            if (shrinkType != 'img') {
                $("#shrink_content").empty();
            }
            $("#shrink_outer").animate(itemOpts, 500, function() {
                $(".blockLY").hide();
                $("#shrink_close").unbind('click');
                if (opts.isrecommend)
                    $(".live").hide();
            });
        },
        getViewParam: function() {
            return {
                'width': document.documentElement.clientWidth,
                'height': document.documentElement.clientHeight
            };
        },
        getCenterPx: function(elem) {
            var vp = this.getViewParam();
            var width = (vp.width - elem._width) / 2;
            var height = (vp.height - elem._height) / 2 + Math.max(document.documentElement.scrollTop, document.body.scrollTop);
            return {
                'width': width,
                'height': height
            };
        },
        getPageParam: function() {
            var pageWidth = document.documentElement.clientWidth;
            var pageHeight = document.documentElement.scrollHeight > document.documentElement.clientHeight ? document.documentElement.scrollHeight: document.documentElement.clientHeight;
            return {
                'width': pageWidth,
                'height': pageHeight
            };
        },
        fetchOffset: function(obj) {
            var left_offset = obj.offsetLeft;
            var top_offset = obj.offsetTop;
            while ((obj = obj.offsetParent) != null) {
                left_offset += obj.offsetLeft;
                top_offset += obj.offsetTop;
            }
            return {
                'left': left_offset,
                'top': top_offset
            };
        },
        createHideLayer: function() {
            var hidelayerObj = $("#hidelayer");
            if (!hidelayerObj.length) {
                var hideLayerDiv = $('<DIV class="blockLY" id="hidelayer" style="display:none"></DIV>');
                hideLayerDiv.css({
                    "padding": 0,
                    "margin": 0,
                    "zIndex": 100,
                    "position": "fixed",
                    "width": "100%",
                    "height": "100%",
                    "background-color": "#666",
                    "top": 0,
                    "left": 0
                });
                if (YU.is_Ie6) {
                    var page = YU.getPageParam();
                    hideLayerDiv.css({
                        "position": "absolute",
                        "width": page.width + "px",
                        "height": page.height + "px"
                    });
                    $(window).bind("scroll resize", function() {
                        var page = YU.getPageParam();
                        hideLayerDiv.css({
                            "width": page.width + "px",
                            "height": page.height + "px"
                        });
                    })
                    }
                hideLayerDiv.appendTo("body").css("opacity", 0.6);
                //opts.hidelayerOpacity
                } else {
                hidelayerObj.show();
            }
        },
        setDrag: function(objid, objid2) {
            var pX, pY, sX, sY, isdrag = false, index = 50, dragObj = {};
            document.onmouseup = mouseUpHandle;
            document.onmousemove = mouseMoveHandle;
            var Obj = (typeof objid == "object") ? $(objid) : jQuery("#" + objid);
            Obj.css("cursor", "move").mousedown(function(oEvent) {
                var aEvent = window.event ? window.event: oEvent;
                isdrag = true;
                dragObj = document.getElementById(objid2);
                if (dragObj.setCapture)
                    dragObj.setCapture();
                objId = objid2;
                sY = parseInt(dragObj.style.top + 0);
                sX = parseInt(dragObj.style.left + 0);
                pX = aEvent.clientX;
                pY = aEvent.clientY;
                if (aEvent.preventDefault)
                    aEvent.preventDefault();
            });
            function mouseMoveHandle(oEvent) {
                if (isdrag) {
                    var aEvent = window.event ? window.event: oEvent;
                    dragObj.style.left = (sX + aEvent.clientX - pX) + "px";
                    dragObj.style.top = (sY + aEvent.clientY - pY) + "px";
                    if (aEvent.preventDefault)
                        aEvent.preventDefault();
                }
            }
            function mouseUpHandle(oEvent) {
                if (isdrag) {
                    var aEvent = window.event ? window.event: oEvent;
                    if (dragObj.releaseCapture)
                        dragObj.releaseCapture();
                    if (aEvent.preventDefault)
                        aEvent.preventDefault();
                    isdrag = false;
                    dragObj = {};
                }
            }
        }
    };
    $(document).ready(function() {
        $.shrink.impl.build();
    });
})(jQuery);