﻿/*
20100825
*/
var Site={
  version : '1.0.0'
}
Site.$=function(id){
    if(typeof id=="string")return document.getElementById(id);
    return id;
}
Site.browser=function(){
     var ua= navigator.userAgent;
    if(ua.indexOf('MSIE 6.0')>0)
       return 'IE6'
    if(ua.indexOf('MSIE 7.0')>0)
       return 'IE7'
    return null;
}
Site.onReady = function(fn) {
    window.onload = fn;
}
Site.getBody=function(){
    if(document.body)
        return document.body;
    if(document.documentElement) return document.documentElement;
    return Site.getElements("","body")[0];
}
/*根据类名或者标签名获取元素列表
  className:类
  tagname:标签名
  root:元素
*/
Site.getElements=function(className,tagname,root){
    //如果root没定义，则等于document
    if (!root) root = document;
    else if (typeof root == "string") root = Site.$(root);
    
    //如果没有tagname,则获取所有的tag
    if (!tagname) tagname = "15-";
    var all = root.getElementsByTagName(tagname);
    //如果没有classname,则返回tagname
    if(!className) return all;
    
    //如果有classname则，进行classname获取all的class=classname的标签数组
    var elements = [];
    for(var i = 0; i < all.length; i++) {
        var element = all[i];
        if (Site.isHaveClass(element, className)) // isMember() is defined below
            elements.push(element);       // Add class members to our array
    }
    return elements;
}
/*
检查一个calssName是否存在元素中，或者元素是否有这个calssName
*/
Site.isHaveClass=function(element,classname){
    var classes = element.className;
    if (!classes) return false;
    if (classes == classname) return true; 
        
    //如果是空格
    var whitespace = /\s+/;//空格正则表达式
    //如果没空格，则返回
    if (!whitespace.test(classes)) return false;
    var c = classes.split(whitespace);  // Split with whitespace delimiter
    for(var i = 0; i < c.length; i++) { // Loop through classes
       if (c[i] == classname) return true;  // and check for matches
    }
    return false;  // None of the classes matched
}
/*
创建一个元素
tagname:要创建的标签名称;attributes:要添加的属性如：{id:'a',href:'..'},children:[elements]或者文本
*/
Site.createElement = function(tagname, attributes, children) {
    //如果只有两个参数，且第字符串和数组，则是要添加的元素和子元素
    if (arguments.length == 2 && (attributes instanceof Array || typeof attributes == "string")) {
        children = attributes;
        attributes = null;
    }
    var e = document.createElement(tagname);
    //设置属性
    if (attributes) {
        for (var name in attributes) {
            if (name == 'style')//如果是样式属性
            {
                for (var s in attributes.style) {
                    e.style[s] = attributes.style[s];
                }
            }
            else {
                if (e[name] != null)
                    e[name] = attributes[name];
            }
        }
        if (attributes.listeners)//添加事件{click:function(){},.....}
        {
            for (var name in attributes.listeners) {
                Site.Handler.add(e, name, attributes.listeners[name]);
            }
        }
    }
    //设置子元素
    if (children != null) {
        if (children instanceof Array) {
            for (var i = 0; i < children.length; i++) { // Loop through kids
                var child = children[i];
                if (typeof child == "string")          // Handle text nodes
                    child = document.createTextNode(child);
                e.appendChild(child);  // Assume anything else is a Node
            }
        }
        else if (typeof children == "string") // Handle single text child
            e.appendChild(document.createTextNode(children));
        else e.appendChild(children);         // Handle any other single child
    }

    return e;
}
/*
事件操作
*/
Site.Handler={};
if (document.addEventListener) {
    Site.Handler.add = function(element, eventType, handler) {
        element.addEventListener(eventType, handler, false);
    };

    Site.Handler.remove = function(element, eventType, handler) {
        element.removeEventListener(eventType, handler, false);
    };
}//ie
else if (document.attachEvent) {
    Site.Handler.add = function(element, eventType, handler) {
        //如果该事件存在，则返回
        if (Site.Handler._find(element, eventType, handler) != -1) return;
        //定义事件本身函数
        var wrappedHandler = function(e) {
            if (!e) e = window.event;
            // Create a synthetic event object with partial compatibility
            // with DOM events.
            var event = {
                _event: e,    // In case we really want the IE event object
                type: e.type,           // Event type
                target: e.srcElement,   // Where the event happened
                currentTarget: element, // Where we're handling it
                relatedTarget: e.fromElement?e.fromElement:e.toElement,
                eventPhase: (e.srcElement==element)?2:3,

                // Mouse coordinates
                clientX: e.clientX, clientY: e.clientY,
                screenX: e.screenX, screenY: e.screenY,
               // Key state
                altKey: e.altKey, ctrlKey: e.ctrlKey,
                shiftKey: e.shiftKey, charCode: e.keyCode,

                // Event-management functions
                stopPropagation: function( ) {this._event.cancelBubble = true;},
                preventDefault: function( ) {this._event.returnValue = false;}
            }

            // Invoke the handler function as a method of the element, passing
            // the synthetic event object as its single argument.
            // Use Function.call( ) if defined; otherwise do a hack
            if (Function.prototype.call)
                handler.call(element, event);
            else {
                // If we don't have Function.call, fake it like this.
                element._currentHandler = handler;
                element._currentHandler(event);
                element._currentHandler = null;
            }
        };

        // Now register that nested function as our event handler.
        element.attachEvent("on" + eventType, wrappedHandler);

        // Now we must do some record keeping to associate the user-supplied
        // handler function and the nested function that invokes it.
        // We have to do this so that we can deregister the handler with the
        // remove( ) method and also deregister it automatically on page unload.

        // Store all info about this handler into an object.
        var h = {
            element: element,
            eventType: eventType,
            handler: handler,
            wrappedHandler: wrappedHandler
        };

        // Figure out what document this handler is part of.
        // If the element has no "document" property, it is not
        // a window or a document element, so it must be the document
        // object itself.
        var d = element.document || element;
        // Now get the window associated with that document.
        var w = d.parentWindow;

        // We have to associate this handler with the window,
        // so we can remove it when the window is unloaded.
        var id = Site.Handler._uid( );  // Generate a unique property name
        if (!w._allHandlers) w._allHandlers = {};  // Create object if needed
        w._allHandlers[id] = h; // Store the handler info in this object

        // And associate the id of the handler info with this element as well.
        if (!element._handlers) element._handlers = [];
        element._handlers.push(id);

        // If there is not an onunload handler associated with the window,
        // register one now.
        if (!w._onunloadHandlerRegistered) {
            w._onunloadHandlerRegistered = true;
            w.attachEvent("onunload", Site.Handler._removeAllHandlers);
        }
    };

    Site.Handler.remove = function(element, eventType, handler) {
        // Find this handler in the element._handlers[] array.
        var i = Site.Handler._find(element, eventType, handler);
        if (i == -1) return;  // If the handler was not registered, do nothing

        // Get the window of this element.
        var d = element.document || element;
        var w = d.parentWindow;

        // Look up the unique id of this handler.
        var handlerId = element._handlers[i];
        // And use that to look up the handler info.
        var h = w._allHandlers[handlerId];
        // Using that info, we can detach the handler from the element.
        element.detachEvent("on" + eventType, h.wrappedHandler);
        // Remove one element from the element._handlers array.
        element._handlers.splice(i, 1);
        // And delete the handler info from the per-window _allHandlers object.
        delete w._allHandlers[handlerId];
    };

    // A utility function to find a handler in the element._handlers array
    // Returns an array index or -1 if no matching handler is found
    Site.Handler._find = function(element, eventType, handler) {
        var handlers = element._handlers;
        if (!handlers) return -1;  // if no handlers registered, nothing found

        // Get the window of this element
        var d = element.document || element;
        var w = d.parentWindow;

        // Loop through the handlers associated with this element, looking
        // for one with the right type and function.
        // We loop backward because the most recently registered handler
        // is most likely to be the first removed one.
        for(var i = handlers.length-1; i >= 0; i--) {
            var handlerId = handlers[i];        // get handler id
            var h = w._allHandlers[handlerId];  // get handler info
            // If handler info matches type and handler function, we found it.
            if (h.eventType == eventType && h.handler == handler)
                return i;
        }
        return -1;  // No match found
    };

    Site.Handler._removeAllHandlers = function( ) {
        // This function is registered as the onunload handler with
        // attachEvent. This means that the this keyword refers to the
        // window in which the event occurred.
        var w = this;

        // Iterate through all registered handlers
        for(id in w._allHandlers) {
            // Get handler info for this handler id
            var h = w._allHandlers[id];
            // Use the info to detach the handler
            h.element.detachEvent("on" + h.eventType, h.wrappedHandler);
            // Delete the handler info from the window
            delete w._allHandlers[id];
        }
    }

    // Private utility to generate unique handler ids
    Site.Handler._counter = 0;
    Site.Handler._uid = function( ) { return "h" + Site.Handler._counter++; };
}
//Site.onReady = function(fn) {
//    Site.Handler.add(document.body, "load", fn);
//}
/* end envent hanlder*/
/*
  start Site.Ajax 
*/
/*
url:请求的;success:function(json){};action:'post'||'get';errerHanlder:function(status,statusText){}
 parameters:{field:value}在get的时候, values:{field:value}post的时候，
timeout:设置多少毫秒超时；timeoutHandler:function(){超时后的函数}；progressHandler:function(n){请求中的函数}
,success:function(json){...}, errorHandler:function(status,statusText){..}}
*/
Site.Ajax=function(configs){
    this.configs=configs;
}
Site.Ajax.prototype.request=function(){
    var request=this.httpObject();
    if(this.configs.action=='get'){
        this.get(this.configs);
    }
    else if (this.configs.action == 'post') {
        this.post(this.configs);
    } 
}
/*
 post一个请求
*/
Site.Ajax.prototype.post= function(configs) {
    var request = this.httpObject();
    var n=0;
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (request.status == 200) {
                configs.success(Site.Ajax._getResponse(request));
            }
            else {
                if (configs.errorHandler) configs.errorHandler(request.status,
                                               request.statusText);
                else configs.success(null);
            }
        }
        else if(configs.progressHandler){
            configs.progressHandler(++n);
        }
    }
    var target = configs.url;
    if (configs.parameters)
        target += "?" + this.encodeFormData(configs.parameters)
    request.open("POST", target);
    // This header tells the server how to interpret the body of the request.
    request.setRequestHeader("Content-Type",
                             "application/x-www-form-urlencoded;charset=UTF-8");
    // Encode the properties of the values object and send them as
    // the body of the request.
    request.send(this.encodeFormData(configs.values));
};
/* configs:{url, parameters:{field:value}, success:function(json){...}, errorHandler:function(status,statusText){..}};
timeout:设置多少毫秒超时；timeoutHandler:function(){超时后的函数}；progressHandler:function(n){请求中的函数}
*/
Site.Ajax.prototype.get = function(configs) {
    var request = this.httpObject();
    var n = 0;
    var timer;
    if (configs.timeout)
        timer = setTimeout(function() {
                               request.abort();//停止请求
                               if (request.timeoutHandler)
                                   request.timeoutHandler(url);
                           },
                           request.timeout);
    request.onreadystatechange = function() {
        if (request.readyState == 4) {
            if (timer) clearTimeout(timer);
            if (request.status == 200) {
                configs.success(Site.Ajax._getResponse(request));
            }
            else {
                if (configs.errorHandler)
                    configs.errorHandler(request.status,
                                         request.statusText);
                else configs.success(null);
            }
        }
        else if (configs.progressHandler) {
            configs.progressHandler(++n);
        }
    }
    var target = configs.url;
    if (configs.parameters)
        target += "?" + this.encodeFormData(configs.parameters)
    request.open("GET", target);
    request.send(null);
};
Site.Ajax.prototype._httpObjects= [
    function() { return new XMLHttpRequest(); },
    function() { return new ActiveXObject("Msxml2.XMLHTTP"); },
    function() { return new ActiveXObject("Microsoft.XMLHTTP"); }
];
Site.Ajax.prototype.httpObject = function() {
    if (this._httpObject != null) return this._httpObject();
    for(var i = 0; i < this._httpObjects.length; i++) {
        try {
              this._httpObject= this._httpObjects[i];
              return this._httpObject();
        }
        catch(e) {
            continue;
        }
    }
    this._httpObject = function() {
        throw new Error("XMLHttpRequest not supported");
    }
    this._httpObject();//跳出异常
}
/*
输出对象
*/
Site.Ajax._getResponse = function(request) {
    // Check the content type returned by the server
    var responseHeader = request.getResponseHeader("Content-Type");
    if (responseHeader.indexOf("text/xml") >= 0) return request.responseXML;
    else if (responseHeader.indexOf("text/json") >= 0 || responseHeader.indexOf("text/javascript") >= 0
            || responseHeader.indexOf("application/javascript") >= 0 || responseHeader.indexOf("application/x-javascript") >= 0) {
        try {
            return eval(request.responseText);
        } catch (e) {
            return eval("({errors:'请检查输出数据是不是可执行的javascript,errors：" + e.message + "!'})"); //如果
        }

    } else {
        return request.responseText;
    }
};
/**
 * Encode the property name/value pairs of an object as if they were from
 * an HTML form, using application/x-www-form-urlencoded format
 */
Site.Ajax.prototype.encodeFormData = function(data) {
    var pairs = [];
    var regexp = /%20/g; // A regular expression to match an encoded space
    for(var name in data) {
        var value = data[name].toString();
        // Create a name/value pair, but encode name and value first
        // The global function encodeURIComponent does almost what we want,
        // but it encodes spaces as %20 instead of as "+". We have to
        // fix that with String.replace()
        var pair = encodeURIComponent(name).replace(regexp,"+") + '=' +
            encodeURIComponent(value).replace(regexp,"+");
        pairs.push(pair);
    }
    // Concatenate all the name/value pairs, separating them with &
    return pairs.join('&');
};
/* end ajax */
/*获取window的内置的高度和宽度*/
if (window.screenLeft) { // IE and others
    Site.getWindowX = function( ) { return window.screenLeft; };
    Site.getWindowY = function( ) { return window.screenTop; };
}
else if (window.screenX) { // Firefox and others
    Site.getWindowX = function( ) { return window.screenX; };
    Site.getWindowY = function( ) { return window.screenY; };
}

if (window.innerWidth) { // All browsers but IE
    Site.getViewportWidth = function( ) { return window.innerWidth; };
    Site.getViewportHeight = function( ) { return window.innerHeight; };
    Site.getHorizontalScroll = function( ) { return window.pageXOffset; };
    Site.getVerticalScroll = function( ) { return window.pageYOffset; };
}
else if (document.documentElement && document.documentElement.clientWidth) {
    // These functions are for IE 6 when there is a DOCTYPE
    Site.getViewportWidth =
        function( ) { return document.documentElement.clientWidth; };
    Site.getViewportHeight =
        function( ) { return document.documentElement.clientHeight; };
    Site.getHorizontalScroll =
        function( ) { return document.documentElement.scrollLeft; };
    Site.getVerticalScroll =
        function( ) { return document.documentElement.scrollTop; };
}
else if (document.body.clientWidth) {
    // These are for IE4, IE5, and IE6 without a DOCTYPE
    Site.getViewportWidth =
        function( ) { return document.body.clientWidth; };
    Site.getViewportHeight =
        function( ) { return document.body.clientHeight; };
    Site.getHorizontalScroll =
        function( ) { return document.body.scrollLeft; };
    Site.getVerticalScroll =
        function( ) { return document.body.scrollTop; };
}

// These functions return the size of the document. They are not window
// related, but they are useful to have here anyway.
if (document.documentElement && document.documentElement.scrollWidth) {
    Site.getDocumentWidth =
        function( ) { return document.documentElement.scrollWidth; };
    Site.getDocumentHeight =
        function( ) { return document.documentElement.scrollHeight; };
}
else if (document.body.scrollWidth) {
    Site.getDocumentWidth =
        function( ) { return document.body.scrollWidth; };
    Site.getDocumentHeight =
        function( ) { return document.body.scrollHeight; };
} else if(window.innerHeight){
    Site.getDocumentHeight=function(){
        return window.innerHeight;
    }
    Site.getDocumentWidth=function(){
        return window.innerWidth;
    }
}
/*end 获取window的内置的高度和宽度*/
/*start 获取元素的位置*/
Site.getElementX=function(e){
    var offset=e.offsetLeft; 
    if(e.offsetParent!=null) offset+=Site.getElementX(e.offsetParent); 
     return offset; 
}
Site.getElementY=function(e){
     var offset=e.offsetTop; 
     if(e.offsetParent!=null) offset+=Site.getElementY(e.offsetParent); 
     return offset; 
}
/*end 获取元素的位置*/
/*---------------------------HTML HTMLEncode HTMLDecode-------------------------------------------*/
Site.HTMLEncode=function(html)//对HTML进行编码
{
    var temp = document.createElement ("div");
    (temp.textContent != null) ? (temp.textContent = html) : (temp.innerText = html);
    var output = temp.innerHTML;
    temp = null;
    return output;
}
Site.HTMLDecode=function(text)//对HTML进行解码
{
    var temp = document.createElement("div");
    temp.innerHTML = text;
    var output = temp.innerText || temp.textContent;
    temp = null;
    return output;
}
/*------------------------------------end-- HTMLEncode HTMLDecode-------------------------------------------------------*/
