﻿/// <reference path="jquery-1.4.1-vsdoc.js" />
/// <reference path="jquery-jtemplates.js" />

(function ($) {
    $.extend({
        accessbarSettings: {},
        //Cookies操作
        accessbarCookie: function (name, value, options) {
            if (typeof value != 'undefined') {
                options = options || { path: "/" };
                if (value === null) {
                    value = '';
                    options.expires = -1;
                }
                var expires = '';
                if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
                    var date;
                    if (typeof options.expires == 'number') {
                        date = new Date();
                        date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
                    } else {
                        date = options.expires;
                    }
                    expires = '; expires=' + date.toUTCString();
                }
                var path = options.path ? '; path=' + (options.path) : '';
                var domain = options.domain ? '; domain=' + (options.domain) : '';
                var secure = options.secure ? '; secure' : '';
                document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
            } else {
                var cookieValue = null;
                if (document.cookie && document.cookie != '') {
                    var cookies = document.cookie.split(';');
                    for (var i = 0; i < cookies.length; i++) {
                        var cookie = jQuery.trim(cookies[i]);
                        if (cookie.substring(0, name.length + 1) == (name + '=')) {
                            cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                            break;
                        }
                    }
                }
                return cookieValue;
            }
        },
        accessbar: {

            texttospeechControl: function () {
                if ($.accessbarCookie("texttospeechState") != "1") {

                    $("#texttospeech").attr("value", "关闭语音");
                    $("#texttospeech").attr("title", "关闭语音");

                    $.accessbarCookie("texttospeechState", 1);

                    $("#audioplayerContainer").show();
                }
                else {

                    $("#texttospeech").attr("value", "开启语音");
                    $("#texttospeech").attr("title", "开启语音");

                    $.accessbarCookie("texttospeechState", 0);

                    $("#audioplayerContainer").hide();
                }
            },
            pageZoomControl: function () {
                if ($.accessbarCookie("pageZoomState") == "1") {
                    $.accessbarSettings.defaultPageSize = $.accessbarSettings.defaultPageSize + 0.2;
                    if ($.accessbarSettings.defaultPageSize > 2) { $.accessbarSettings.defaultPageSize = 2; };
                }
                else {
                    $.accessbarSettings.defaultPageSize = $.accessbarSettings.defaultPageSize - 0.2;
                    if ($.accessbarSettings.defaultPageSize < 1) { $.accessbarSettings.defaultPageSize = 1; };
                }

                //兼容各浏览器
                if ($.browser.mozilla) {
                    $("body").css("-moz-transform-origin", "top left");
                    $("body").css("-moz-transform", 'scale(' + $.accessbarSettings.defaultPageSize + ',' + $.accessbarSettings.defaultPageSize + ')');
                }
                else if ($.browser.msie || $.browser.safari) {
                    $("body")[0].style.zoom = $.accessbarSettings.defaultPageSize;
                    $("body")[0].style.overflow = "scroll";
                }
                else if ($.browser.opera) {
                    $("body").css("-o-transform-origin", "top left");
                    $("body").css("-o-transform", 'scale(' + $.accessbarSettings.defaultPageSize + ',' + $.accessbarSettings.defaultPageSize + ')');
                }
            },

            openDeclareControl: function () {
                window.open($.accessbarSettings.operateExplainURL);
            },

            //重置
            resetToolBarControl: function () {
                $.accessbarCookie("toolBarState", 1);
                $.accessbarCookie("pageFontSize", $.accessbarSettings.defaultFontSize);
                $.accessbarCookie("contrastState", 0);
                $.accessbarCookie("pageZoomState", 1);
                $.accessbarCookie("guidesState", 0);
                $.accessbarCookie("textModeState", 0);
                window.location.reload();
            },

            //字体大小控制
            fontSizeZoomControl: function () {
                if ($.accessbarCookie("fontSizeZoomState") == "1") {
                    var fontSize = 2 + parseInt($.accessbarCookie("pageFontSize"));
                    if (fontSize >= $.accessbarSettings.maxFontSize) {
                        fontSize = $.accessbarSettings.maxFontSize;
                    }
                    $("body *").accessbarFilter().css("font-size", fontSize + "px").css("line-height", fontSize + 2 + "px");
                    $.accessbarCookie("pageFontSize", fontSize);
                }
                else {
                    var fontSize = $.accessbarCookie("pageFontSize") - 2;
                    if (fontSize <= $.accessbarSettings.minFontSize) {
                        fontSize = $.accessbarSettings.minFontSize;
                    }
                    $("body *").accessbarFilter().css("font-size", fontSize + "px").css("line-height", fontSize + 2 + "px");
                    $.accessbarCookie("pageFontSize", fontSize);
                }
            },

            //高对比度
            highContrastControl: function () {
                if ($.accessbarCookie("contrastState") != "1") {
                    $('*').accessbarFilter().attr("ocolor", function () { if ($(this).attr("ocolor")) { return $(this).attr("ocolor") } else { return $(this).css("color"); } }).attr("obackgroundcolor", function () { return $(this).css("background-color"); }).css("color", "#FFF").css("background-color", "#000");

                    $("#contrasbutton").attr("value", "还原对比度");
                    $("#contrasbutton").attr("title", "还原对比度");

                    $.accessbarCookie("contrastState", 1);
                }
                else {
                    $('*').accessbarFilter().css("color", function () { if ($(this).attr("ocolor")) { return $(this).attr("ocolor") } else { return $(this).css("color"); } }).css("background-color", function () { if ($(this).attr("obackgroundcolor")) { return $(this).attr("obackgroundcolor") } else { return $(this).css("background-color"); } });

                    $("#contrasbutton").attr("value", "高对比度");
                    $("#contrasbutton").attr("title", "高对比度");

                    $.accessbarCookie("contrastState", 0);
                }
            },


            //纯文本模式
            textModeControl: function () {
                if ($.accessbarCookie("textModeState") != "1") {
                    $("link").each(function () {
                        if ($(this).attr("href") != $.accessbarSettings.accessbarStyleLink) {
                            $(this).remove();
                        }
                    });


                    $("body img").each(function () {
                        $("<span></span>").text($(this).attr("alt") ? $(this).attr("alt") : $(this).attr("title")).insertBefore($(this));
                        $(this).remove();
                    });


                    $("body input[type='image']").each(function () {
                        $("<span></span>").text($(this).attr("alt") ? $(this).attr("alt") : $(this).attr("title")).insertBefore($(this));
                        $(this).remove();
                    });


                    $("body iframe").remove();

                    $("*").accessbarFilter().removeAttr("style");

                    $('<link rel="Stylesheet" type="text/css" href="' + $.accessbarSettings.textModeStyleLink + '" />').appendTo("head");

                    if ($("#textmodebutton")) { $("#textmodebutton").attr("value", "切换为可视模式"); }
                    if ($("#textmodebutton")) { $("#textmodebutton").attr("title", "切换为可视模式"); }

                    $.accessbarCookie("textModeState", 1);
                    $.accessbarCookie("textModeReloadState", 0);
                }
                else {
                    $.accessbarCookie("textModeState", 0);
                    if ($.accessbarCookie("textModeReloadState") != "1") {
                        $.accessbarCookie("textModeReloadState", 1);
                        window.location.reload();
                    }
                }
            },

            //辅助线功能
            guidesControl: function () {
                if ($.accessbarCookie("guidesState") != "1") {
                    var guidesElement = $("<div>", { "id": "guides", "style": "display:none;z-index:199;" });
                    var toolbarStatus = { template: "guides" };
                    guidesElement.setTemplateURL($.accessbarSettings.templateUrl, null, { filter_data: false });
                    guidesElement.processTemplate(toolbarStatus);
                    guidesElement.prependTo("body");

                    $("#guides").css("display", "block");
                    $("#guidesYLine").css("height", $(document).height() + "px").css("width", $.accessbarSettings.guidesWidth + "px").css("background-color", $.accessbarSettings.guidesColor);
                    $("#guidesXLine").css("height", $.accessbarSettings.guidesWidth + "px").css("background-color", $.accessbarSettings.guidesColor);

                    $(document).mousemove(function (e) {
                        if ($.accessbarCookie("guidesState") != "1") { return false; };
                        $("#guidesYLine").css("left", $.browser.msie ? (e.clientX + (document.documentElement.scrollLeft || document.body.scrollLeft)) + $.accessbarSettings.guidesSkew + "px" : e.pageX + $.accessbarSettings.guidesSkew + "px");
                        $("#guidesXLine").css("top", $.browser.msie ? (e.clientY + document.documentElement.scrollTop || document.body.scrollTop) + $.accessbarSettings.guidesSkew + "px" : e.pageY + $.accessbarSettings.guidesSkew + "px");
                    });

                    if ($("#guidesbutton").length > 0) {
                        $("#guidesbutton").attr("value", "关闭辅助线").attr("title", "关闭辅助线");
                    }
                    $.accessbarCookie("guidesState", 1);
                }
                else {
                    $("#guides").css("display", "none");
                    $("#guides").remove();
                    if ($("#guidesbutton").length > 0) {
                        $("#guidesbutton").attr("value", "开启辅助线").attr("title", "开启辅助线");
                    }
                    $.accessbarCookie("guidesState", 0);
                }
            },

            //状态栏
            toolBarControl: function () {
                if ($.accessbarCookie("toolBarState") != "1") {
                    var toolbar = $("<div>", { "id": "toolbar" });
                    var toolbarStatus = { template: "toolBar" };
                    toolbar.setTemplateURL($.accessbarSettings.templateUrl, null, { filter_data: false });
                    toolbar.processTemplate(toolbarStatus);
                    toolbar.prependTo("body");

                    $.accessbarCookie("toolBarState", "1");

                    $("#guidesbutton").click($.accessbar.guidesControl);
                    if ($.accessbarCookie("guidesState") == "1") {
                        $("#guidesbutton").attr("value", "关闭辅助线").attr("title", "关闭辅助线");
                    }

                    if ($.accessbarCookie("texttospeechState") == "1") {
                        $("#texttospeech").attr("value", "关闭语音").attr("title", "关闭语音");
                    }

                    $("#contrasbutton").click($.accessbar.highContrastControl);

                    $("#textmodebutton").click($.accessbar.textModeControl);

                    $("#fontSizeZoomIn").click(function () {
                        $.accessbarCookie("fontSizeZoomState", 1);
                        $.accessbar.fontSizeZoomControl();
                    });

                    $("#fontSizeZoomOut").click(function () {
                        $.accessbarCookie("fontSizeZoomState", 0);
                        $.accessbar.fontSizeZoomControl();
                    });

                    $("#pageZoomIn").click(function () {
                        $.accessbarCookie("pageZoomState", 1);
                        $.accessbar.pageZoomControl();
                    });

                    $("#pageZoomOut").click(function () {
                        $.accessbarCookie("pageZoomState", 0);
                        $.accessbar.pageZoomControl();
                    });

                    $("#toolBarControl").click($.accessbar.toolBarControl);

                    $("#resetToolBar").click($.accessbar.resetToolBarControl);

                    $("#openDeclare").click($.accessbar.openDeclareControl);

                    $("#texttospeech").click($.accessbar.texttospeechControl);
                }
                else {
                    $("#toolbar").remove();
                    document.body.style.paddingTop = 0 + "px";
                    $.accessbarCookie("toolBarState", "0");
                }
            },

            //监听键盘事件
            keyListener: function (event) {
                var currkey = event.keyCode || event.which || event.charCode;
                if (event.altKey && !event.shiftKey && !event.ctrlKey) {
                    if (currkey == $.accessbarSettings.toolBarControlKey) {
                        $.accessbar.toolBarControl();
                    };
                    if (currkey == $.accessbarSettings.guidesControlKey) {
                        $.accessbar.guidesControl();
                    };
                    if (currkey == $.accessbarSettings.skipToHeaderAreaKey) {
                        //buildAreaSkipElement(header, headerSkipElementHTML);
                        //buildAreaSkipElement(otherheader, headerSkipElementHTML);
                    };
                    if (currkey == $.accessbarSettings.skipToContentAreaKey) {
                        //skipToMain(); 
                    };
                    if (currkey == $.accessbarSettings.columnSkipKey) {
                        //skipToNextColumn(); 
                    };
                    if (currkey == $.accessbarSettings.skipToLeftAreaKey) {
                        //buildAreaSkipElement(leftSideBar, leftSideBarSkipElementHTML);
                    };
                    if (currkey == $.accessbarSettings.skipToFooterAreaKey) {
                        //buildAreaSkipElement(footer, footerSkipElementHTML); 
                    };
                    if (currkey == $.accessbarSettings.skipToMainAreaKey) {
                        //skipToCenter(); 
                    };
                }
                if (event.altKey && event.shiftKey && !event.ctrlKey) {
                    if (currkey == $.accessbarSettings.textModeControlKey) {
                        //textMode(true); 
                    };
                    if (currkey == $.accessbarSettings.columnSkipKey) {
                        //skipToPreviousColumn(); 
                    };
                }
                if (event.altKey && !event.shiftKey && event.ctrlKey) {
                    if (currkey == $.accessbarSettings.textModeControlKey) {
                        //textMode(false);
                    };
                    if (currkey == $.accessbarSettings.skipToContentAreaKey) {
                        //skipToMain(); 
                    };
                }
                if (!event.altKey && !event.shiftKey && event.ctrlKey) {
                    if (currkey == $.accessbarSettings.columnSkipKey) {
                        //skipToNextColumn(); 
                    };
                }
                if (!event.altKey && event.shiftKey && event.ctrlKey) {
                    if (currkey == $.accessbarSettings.columnSkipKey) {
                        //skipToPreviousColumn();
                    };
                }
                if (event.altKey && event.shiftKey && event.ctrlKey) {
                    if (currkey == $.accessbarSettings.skipToLeftAreaKey) {
                        //buildAreaSkipElement(leftSideBar, leftSideBarSkipElementHTML); 
                    };
                    if (currkey == $.accessbarSettings.skipToFooterAreaKey) {
                        //buildAreaSkipElement(footer, footerSkipElementHTML); 
                    };
                    if (currkey == $.accessbarSettings.skipToMainAreaKey) {
                        //skipToCenter(); 
                    };
                }
            }
        }
    });


    $.fn.accessbarFilter = function () {
        var idArr = ["toolbar", "guides", "guidesYLine", "guidesXLine", "textmodebutton", "fontSizeZoomIn", "fontSizeZoomOut", "contrasbutton", "guidesbutton", "pageZoomIn", "pageZoomOut", "openDeclare", "resetToolBar", "toolBarControl", "texttospeech"];
        return this.filter(function (index) {
            return $.inArray($(this).attr("id"), idArr) == -1;
        });
    };

    $.fn.accessbar = function (options) {
        var settings = {
            "toolBarControlKey": 74, 	    //工具条开启（J键）
            "guidesControlKey": 71,         //跳到头部区域（g键）
            "textModeControlKey": 74, 	    //纯文本通道控制（J键）
            "columnSkipKey": 90, 	        //栏目跳转（z键）
            "skipToHeaderAreaKey": 75, 	    //跳到头部区域（k键）
            "skipToMainAreaKey": 77, 		//跳到中间内容区域（m键）
            "skipToLeftAreaKey": 76, 		//跳到左侧区域（l键）
            "skipToContentAreaKey": 67, 	//跳到主要内容区域（c键）
            "skipToRightAreaKey": 100, 	    //跳到右侧区域（J键）
            "skipToFooterAreaKey": 66, 	    //跳到底部区域（b键）

            "header": "header", 			//头部
            "otherheader": "head", 		    //头部例外
            "main": "main", 				//内容区域
            "leftSideBar": "leftcolumn", 	//左侧
            "content": "content", 		    //主要内容区
            "rightSideBar": "rightcolumn",  //右侧
            "footer": "footer", 			//底部
            "articleBox": "mainpage", 	    //内容页正文容器
            "skipClassName": "columnjump",  //跳转节点的class名

            "defaultFontSize": 12, 		    //初始页面字号
            "maxFontSize": 24, 			    //页面最大字号
            "minFontSize": 8, 			    //页面最小字号
            "defaultPageSize": 1,

            "guidesWidth": 4, 			    //辅助线宽度
            "guidesColor": "#F00", 		    //辅助线颜色
            "guidesSkew": -10, 			    //辅助线相对鼠标指针偏移量

            "operateExplainURL": "",
            "iframeKeyListenerFilesSrc": "iframeKeyListener.js",
            "textModeStyleLink": "textmode.css",
            "accessbarStyleLink": "accessbar.css",
            "templateUrl": "accessbar.htm"
        };

        if (options) {
            $.extend(settings, options);
        }
        var init = function () {
            if ($.accessbarCookie("toolBarState") == "1") {
                $.accessbarCookie("toolBarState", 0);
                $.accessbar.toolBarControl();
            }
            else {
                $.accessbarCookie("toolBarState", 1);
                $.accessbar.toolBarControl();
            }

            if ($.accessbarCookie("contrastState") == "1") {
                $.accessbarCookie("contrastState", 0);
                $.accessbar.highContrastControl();
            }
            else {
                $.accessbarCookie("contrastState", 1);
                $.accessbar.highContrastControl();
            }

            if ($.accessbarCookie("textModeState") == "1") {
                $.accessbarCookie("textModeState", 0);
                $.accessbar.textModeControl();
            }
            else {
                $.accessbarCookie("textModeState", 1);
                $.accessbarCookie("textModeReloadState", 1);
                $.accessbar.textModeControl();
            }

            if ($.accessbarCookie("guidesState") == "1") {
                $.accessbarCookie("guidesState", 0);
                $.accessbar.guidesControl();
            }
            else {
                $.accessbarCookie("guidesState", 1);
                $.accessbar.guidesControl();
            }

            if ($.accessbarCookie("texttospeechState") == "1") {
                $.accessbarCookie("texttospeechState", 0);
                $.accessbar.texttospeechControl();
            }
            else {
                $.accessbarCookie("texttospeechState", 1);
                $.accessbar.texttospeechControl();
            }

            $.accessbarCookie("pageFontSize", settings.defaultFontSize);
        };
        $.extend($.accessbarSettings, settings);

        $(document).ready(function () {
            init();

            $(window).keydown($.accessbar.keyListener);

            $("iframe").each(function () {
                var iframeDOM = this.contentWindow;
                try {
                    var scriptElement = iframeDOM.document.createElement("script");
                    scriptElement.setAttribute("type", "text/javascript");
                    scriptElement.setAttribute("src", settings.iframeKeyListenerFilesSrc);
                    iframeDOM.document.getElementsByTagName("head")[0].appendChild(scriptElement);
                } catch (e) { }
            });
        });

        return this.each(function () {
            $(this).bind('click', function () {
                $.accessbar.toolBarControl();
            });
        });
    };
})(jQuery);
