/**
 * @author Will Yuan
 */
var _GMlib = {
    arrLoad: [],
    arrDOMLoad: [],
    browser: new BrowserDetect()
};

//Chceck Browce
function BrowserDetect() {
    var ua = navigator.userAgent.toLowerCase();
    // browser engine name
    this.isGecko = (ua.indexOf('gecko') != -1 && ua.indexOf('safari') == -1);
    this.isAppleWebKit = (ua.indexOf('applewebkit') != -1);
    // browser name
    if (ua.indexOf('opera') != -1) {
        this.isOpera = true;
        this.name = "Opera";
    }
    ;
    if ((ua.indexOf('msie') != -1 && !this.isOpera && (ua.indexOf('webtv') == -1))) {
        this.isIE = true;
        this.name = "Internet Explorer";
    }
    ;
    if (this.isGecko && ua.indexOf('gecko/') + 14 == ua.length) {
        this.isMozilla = true;
        this.name = "Mozilla";
    }
    ;
    if ((this.isGecko) ? (ua.indexOf('netscape') != -1) : ((ua.indexOf('mozilla') != -1) && !this.isOpera && !this.isSafari && (ua.indexOf('spoofer') == -1) && (ua.indexOf('compatible') == -1) && (ua.indexOf('webtv') == -1) && (ua.indexOf('hotjava') == -1))) {
        this.isNS = true;
        this.name = "Netscape";
    }
    ;
    if (ua.indexOf('firebird/') != -1) {
        this.isFirebird = true;
        this.name = "Firebird";
    }
    ;
    if (ua.indexOf('firefox/') != -1) {
        this.isFirefox = true;
        this.name = "FireFox";
    }
    ;
    if (ua.indexOf('safari/') != -1) {
        this.isSafari = true;
        this.name = "Safari";
    }
    ;
    if (ua.indexOf('konqueror') != -1) {
        this.isKonqueror = true;
        this.name = "Konqueror";
    }
    ;
    if (ua.indexOf('omniweb') != -1) {
        this.isOmniweb = true;
        this.name = "Omniweb";
    }
    ;
    if (ua.indexOf('webtv') != -1) {
        this.isWebtv = true;
        this.name = "WebTV";
    }
    ;
    if (ua.indexOf('icab') != -1) {
        this.isICab = true;
        this.name = "Icab";
    }
    ;
    if (ua.indexOf('camino') != -1) {
        this.isCamino = true;
        this.name = "Camino";
    }
    ;
    // spoofing and compatible browsers
    this.isIECompatible = ((ua.indexOf('msie') != -1) && !this.isIE);
    this.isNSCompatible = ((ua.indexOf('mozilla') != -1) && !this.isNS && !this.isMozilla);
    // rendering engine versions
    this.geckoVersion = ((this.isGecko) ? ua.substring((ua.lastIndexOf('gecko/') + 6), (ua.lastIndexOf('gecko/') + 14)) : -1);
    this.equivalentMozilla = ((this.isGecko) ? parseFloat(ua.substring(ua.indexOf('rv:') + 3)) : -1);
    // browser version
    this.versionMinor = parseFloat(navigator.appVersion);
    // correct version number
    if (this.isGecko && !this.isMozilla) {
        if (this.isFirefox) {
            this.versionMinor = parseFloat(ua.substring(ua.indexOf('firefox/') + 8, ua.length));
        }
        else {
            this.versionMinor = parseFloat(ua.substring(ua.indexOf('/', ua.indexOf('gecko/') + 6) + 1));
        }
    }
    else
        if (this.isMozilla)
            this.versionMinor = parseFloat(ua.substring(ua.indexOf('rv:') + 3));
        else
            if (this.isIE && this.versionMinor >= 4)
                this.versionMinor = parseFloat(ua.substring(ua.indexOf('msie ') + 5));
            else
                if (this.isSafari)
                    this.versionMinor = parseFloat(ua.substring(ua.indexOf('safari/') + 7));
                else
                    if (this.isOmniweb)
                        this.versionMinor = parseFloat(ua.substring(ua.indexOf('omniweb/v') + 9));
                    else
                        if (this.isOpera && !this.isMac)
                            this.versionMinor = parseFloat(ua.substring(ua.indexOf('opera') + 6));
    this.versionMajor = parseInt(this.versionMinor);
    // dom support 
    this.isDOM = (document.getElementById && document.createElement ? true : false);
    this.isDOM1 = (document.getElementById ? true : false);
    this.isDOM2Event = (document.addEventListener && document.removeEventListener ? true : false);
    // dhtml support
    this.isDHTML = (document.getElementById || document.all || document.layers ? true : false);
    // css compatibility mode
    this.mode = document.compatMode ? document.compatMode : 'BackCompat';
    // platform
    if (ua.indexOf('win') != -1) {
        this.isWin = true;
        this.platform = "win"
    }
    if (this.isWin && (ua.indexOf('95') != -1 || ua.indexOf('98') != -1 || ua.indexOf('nt') != -1 || ua.indexOf('win32') != -1 || ua.indexOf('32bit') != -1 || ua.indexOf('xp') != -1)) {
        this.isWin32 = true;
        this.platform = "win32"
    }
    if (ua.indexOf('mac') != -1) {
        this.isMac = true;
        this.platform = "mac"
    }
    if (ua.indexOf('x11') != -1) {
        this.isMac = true;
        this.platform = "unix"
    }
    if (ua.indexOf('linux') != -1) {
        this.isMac = true;
        this.platform = "linux"
    }
    // specific browser shortcuts
    this.isNS6x = (this.isNS && this.versionMajor == 6);
    this.isNS6up = (this.isNS && this.versionMajor >= 6);
    this.isNS7x = (this.isNS && this.versionMajor == 7);
    this.isNS7up = (this.isNS && this.versionMajor >= 7);
    this.isIE5x = (this.isIE && this.versionMajor == 5);
    this.isIE55 = (this.isIE && this.versionMinor == 5.5);
    this.isIE5up = (this.isIE && this.versionMajor >= 5);
    this.isIE6x = (this.isIE && this.versionMajor == 6);
    this.isIE6up = (this.isIE && this.versionMajor >= 6);
    this.isIE7up = (this.isIE && this.versionMajor >= 7);
}
;

// Set opacity on an element 
_GMlib.setOpacity = function(obj, opacity) {
    if (opacity === 0) {
        if (obj.style.visibility != "hidden")
            obj.style.visibility = "hidden";
    }
    else {
        if (obj.style.visibility != "visible")
            obj.style.visibility = "visible";
    }
    if (!obj.currentStyle || !obj.currentStyle.hasLayout)
        obj.style.zoom = 1;
    if (_GMlib.browser.isIE) {
        if (opacity === 1) {
            try {
                obj.style.cssText = obj.style.cssText.replace(/filter:[^;]*;/i, "")
            }
            catch (e) {
                obj.style.filter = ''
            }
            ;
        }
        else {
            obj.style.filter = "alpha(opacity=" + opacity * 100 + ")";
        }
    }
    obj.style.opacity = opacity;
};

/* Fix Png For IE6 / 5.5*/
function fixPng() {
    //var arVersion = navigator.appVersion.split("MSIE")
    //var version = parseFloat(arVersion[1])
    if (_GMlib.browser.isIE6x) {
        alert("ie6");
        for (var i = 0; i < document.images.length; i++) {
            var img = document.images[i];
            var imgName = img.src.toUpperCase();
            if (imgName.indexOf(".PNG") > 0) {
                var width = img.width;
                var height = img.height;
                //alert(height);
                var sizingMethod = (img.className.toLowerCase().indexOf("scale") >= 0) ? "scale" : "image";
                img.runtimeStyle.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + img.src.replace('%23', '%2523').replace("'", "%27") + "', sizingMethod='" + sizingMethod + "')";
                //alert("filter");
                img.src = "../../../images/blank.gif";
                //alert(img.src);
                img.width = width;
                img.height = height;
            }
        }
    }
}
;
//Get Element By Id
function $ID(obj) {
    return document.getElementById(obj);
}

//Get Elements By ClassName
function $Class(obj, tag, className) {
    var o = obj.getElementsByTagName(tag);
    for (var i = 0, n = o.length, ret = []; i < n; i++) {
        if (o[i].className == className)
            ret.push(o[i]);
    }
    if (ret.length == 1)
        ret = ret[0];
    return ret;
}
;

//ie6 Menu fix
//function navHover() {
//    var lis = document.getElementById("menu").getElementsByTagName("LI");
//    for (var i = 0; i < lis.length; i++) {
//
//        lis[i].onmouseover = function() {
//            this.className += " iehover";
//        }
//        lis[i].onmouseout = function() {
//            this.className = this.className.replace(new RegExp(" iehover\\b"), "");
//        }
//    }
//}

_GMlib.notContains = function(element, ancestor) {
    if (ancestor.compareDocumentPosition)
    {
        return !(ancestor.compareDocumentPosition(element) & 16) && ancestor !== element;
    }
    else if (ancestor.contains)
    {
        return !ancestor.contains(element);
    }
    return false;
}

_GMlib.firstChtBolder = function(obj, tag) {
    var ret = $ID(obj).getElementsByTagName(tag);
    for (var i = 0; i < ret.length; i++) {
        var txt = ret[i].innerHTML;
        var l = txt.length;
        var tmpStr = txt.substr(0, 1);
        var tmpStrE = txt.substr(1, l);
        var ca = "<span class='fc'>" + tmpStr + "</span>";
        ca = ca + tmpStrE;
        ret[i].innerHTML = ca;
    }
};

_GMlib.animationMgr = function(obj, params) {
    this.initialize(obj, params);
};
_GMlib.animationMgr.prototype = {
    // Initialize object
    initialize: function(obj, params) {
        this.options = params;
        this.options.fps = parseInt(this.options.fps || 50);
        this.options.duration = parseInt(this.options.duration || 0);
        this.elNode = obj;
        this.running = false;
    },
    // Start animation
    start: function(obj) {
        this.running = true;
        this.onStart();
        for (var id in obj)
            this.style = id;
        this.from = obj[id][0];
        this.to = obj[id][1];
        this.change = this.to - this.from,this.now = this.from;
        this.timeStart = _GMlib.getTime();
        this.set(this.from);
        this.timer = window.setInterval(this.tween.bindArgs(this), Math.round(1000 / this.options.fps));
    },
    // Actual tweening
    tween: function() {
        var time = _GMlib.getTime();
        if (time < this.timeStart + this.options.duration) {
            this.now = Math.round(this.options.transition.apply(this, [time - this.timeStart,this.from,this.change,this.options.duration]) * 100) / 100;
            this.set(this.now);
        } else {
            this.set(this.to);
            this.stop();
            this.onComplete();
        }
    },
    // Set he dimensions of the stylet
    set: function(value, obj) {
        obj = obj || this.elNode;
        switch (this.style) {
            case "height":case "left":case "right":case"width":
            obj.style[this.style] = value + 'px';
            break;
            case "opacity":
                _GMlib.setOpacity(obj, value);
                break;
            default:
                obj.style[this.style] = value;
        }
    },
    // Stop animation
    stop: function() {
        window.clearInterval(this.timer);
        this.running = false;
        this.elNode = null;
    },
    // Function to call when the animation is ready
    onComplete: function() {
        if (this.options.onComplete)
            _GMlib.startEvent(this.options, 'onComplete');
    },
    // Function to call when the animation starts
    onStart: function() {
        if (this.options.onStart)
            _GMlib.startEvent(this.options, 'onStart');
    }
};

_GMlib.transition = {
    bounce :
    {
        easeOut: function(t, b, c, d) {
            if ((t /= d) < (1 / 2.75)) {
                return c * (7.5625 * t * t) + b;
            } else if (t < (2 / 2.75)) {
                return c * (7.5625 * (t -= (1.5 / 2.75)) * t + .75) + b;
            } else if (t < (2.5 / 2.75)) {
                return c * (7.5625 * (t -= (2.25 / 2.75)) * t + .9375) + b;
            } else {
                return c * (7.5625 * (t -= (2.625 / 2.75)) * t + .984375) + b;
            }
        },
        easeIn: function (t, b, c, d) {
            return c - _GMlib.transition.bounce.easeOut(d - t, 0, c, d) + b;
        },
        easeInOut:function (t, b, c, d) {
            if (t < d / 2) return _GMlib.transition.bounce.easeIn(t * 2, 0, c, d) * .5 + b;
            else return _GMlib.transition.bounce.easeOut(t * 2 - d, 0, c, d) * .5 + c * .5 + b;
        }
    },
    expo:
    {
        easeIn: function(t, b, c, d) {
            return (t == 0) ? b : c * Math.pow(2, 10 * (t / d - 1)) + b;
        },
        easeOut: function(t, b, c, d) {
            return (t == d) ? b + c : c * (-Math.pow(2, -10 * t / d) + 1) + b;
        },
        easeInOut: function(t, b, c, d) {
            if (t == 0) return b;
            if (t == d) return b + c;
            if ((t /= d / 2) < 1) return c / 2 * Math.pow(2, 10 * (t - 1)) + b;
            return c / 2 * (-Math.pow(2, -10 * --t) + 2) + b;
        }
    },
    linear : function(t, b, c, d)
    {
        return c * t / d + b;
    }
};

// Set opacity on an element
_GMlib.setOpacity = function(obj, opacity) {
    if (opacity === 0) {
        if (obj.style.visibility != "hidden") obj.style.visibility = "hidden";
    } else {
        if (obj.style.visibility != "visible") obj.style.visibility = "visible";
    }
    if (!obj.currentStyle || !obj.currentStyle.hasLayout) obj.style.zoom = 1;
    if (_GMlib.browser.isIE) {
        if (opacity === 1) {
            try {
                obj.style.cssText = obj.style.cssText.replace(/filter:[^;]*;/i, "")
            } catch(e) {
                obj.style.filter = ''
            }
            ;
        } else {
            obj.style.filter = "alpha(opacity=" + opacity * 100 + ")";
        }
    }
    obj.style.opacity = opacity;
};

// Return the current time in seconds
_GMlib.getTime = function() {
    return(new Date().getTime());
};

// GLOBAL FUNCTIONS
_GMlib.startEvent = function(obj, type, args) {
    args = (!args ? arguments : args);
    if (typeof(obj[type]) == "function") {
        obj[type].apply(obj, args);
    }
};

_GMlib.fadeIn = function(o)
{
    var f = new _GMlib.animationMgr(o, {
        duration:500,transition:_GMlib.transition.linear
    })

    f.start({'opacity':[0,1]});
}

_GMlib.fadeOut = function(o)
{
    var f = new _GMlib.animationMgr(o, {
        duration:500,transition:_GMlib.transition.linear
    })

    f.start({'opacity':[1,0]});
}

_GMlib.move = {
    init:function(o, ow, mw) {
        this.ow = ow;
        this.mw = mw;
        this.f = new _GMlib.animationMgr(o, {
            duration:5000,transition:_GMlib.transition.expo.easeInOut
        })
    },
    on:function() {
        this.f.start({'left':[this.ow,this.mw]});
    },
    off:function() {
        this.f.stop();
    }

}

// Extend function class with bindArguments method
Function.prototype.bindArgs = function(scope, args, event) {
    var reference = this;
    return function(e) {
        reference.apply(scope, (event ? (args || []).concat([(e || window.event)]) : (args || arguments) )); // Only append event as last element when args and event has been set.
    }
};


_GMlib.catchEvent = function(e) {
    var cEvent = document.all ? window.event : e;
	if(!_GMlib.browser.isOpera){
    if (document.all) {
        if (cEvent.type == "mouseout") {
            cEvent.relatedTarget = cEvent.toElement;
        }
        else
            if (cEvent.type == "mouseover") {
                cEvent.relatedTarget = cEvent.fromElement;
            }
    }
	}
    return cEvent;
}

//addEventHandler
//function addEventHandler(oTarget, sEventType, fnHandler) {
//    if (oTarget.addEventListener) {
//        oTarget.addEventListener(sEventType, fnHandler, false);
//    } else if (oTarget.attachEvent) {
//        oTarget.attachEvent("on" + sEventType, fnHandler);
//    } else {
//        oTarget["on" + sEventType] = fnHandler;
//    }
//}
//;

if (!document.all) {
    HTMLElement.prototype.attachEvent = function(sType, foo) {
        this.addEventListener(sType.slice(2), foo, false)
    }
}

_GMlib.Events = {
    __listeners: [],
    // Add event 
    add: function(el, type, fn) {
        if (el.addEventListener)
            el.addEventListener(type, fn, false);
        else
            if (el.attachEvent)
                el.attachEvent('on' + type, fn);
        var event = {
            el: el,
            type: type,
            fn: fn
        };
        _GMlib.Events.__listeners.push(event);
        return event;
    },
    // Remove event
    remove: function(el, type, fn) {
        if (el.removeEventListener)
            el.removeEventListener(type, fn, false);
        else
            if (el.detachEvent)
                el.detachEvent('on' + type, fn);
    },
    // Remove SAFELY event to avoid mem leaks, only applicable if you have stored the element
    removeSafe: function(event) {
        if (!event)
            return;
        var el = event.el, i, type = event.type, fn = event.fn;
        _GMlib.Events.remove(el, type, fn);
        for (i = 0; i < this.__listeners.length; i++) {
            if (this.__listeners[i] == event) {
                _GMlib.Events.__listeners.splice(i, 1);
                break;
            }
        }
    },
    // Remove All events 
    removeAll: function() {
        while (_GMlib.Events.__listeners.length > 0)
            _GMlib.Events.removeSafe(_GMlib.Events.__listeners[0]);
    },
    // Cancel event
    cancel: function(e) {
        if (!e)
            e = window.event;
        if (e.stopPropagation)
            e.stopPropagation();
        if (e.preventDefault)
            e.preventDefault();
        e.cancelBubble = true;
        e.cancel = true;
        e.returnValue = false;
        return false;
    },
    // Get target 
    getTarget: function(e) {
        var targ;
        if (!e)
            e = window.event;
        if (e.target)
            targ = e.target;
        else
            if (e.srcElement)
                targ = e.srcElement;
        if (targ.nodeType == 3) // defeat Safari bug
            targ = targ.parentNode;
        return targ;
    }
}

_GMlib.Events.add(window, 'unload', _GMlib.Events.removeAll);

// Add onload event
function addOnLoadEvent(fn) {
    _GMlib.arrLoad[_GMlib.arrLoad.length] = fn;
}
;

// Add DOM onload event fired by end of footer
function addDOMOnLoadEvent(fn) {
    arrDOMLoad[arrDOMLoad.length] = fn;
}
;

// Generic onload handler
function onloadHandler() {
    var k, existing;
    // Load all arrays
    function doLoad(evt) {
        for (k = 0; k < _GMlib.arrLoad.length; k++) {
            try {
                _GMlib.arrLoad[k]()
            }
            catch (err) {
            }
            ;
        }
    }
    //Setup onload function
    if (typeof window.addEventListener != 'undefined') {
        //.. gecko, safari, konqueror and standard
        window.addEventListener('load', function() {
        }, false); // Dummy function inorder to prevent removal of doLoad listner
        window.addEventListener('load', doLoad, false);
    }
    else
        if (typeof document.addEventListener != 'undefined') {
            //.. opera 7
            document.addEventListener('load', doLoad, false);
        }
        else
            if (typeof window.attachEvent != 'undefined') {
                //.. win/ie
                window.attachEvent('onload', doLoad);
            }
            else {
                //.. mac/ie5 and anything else that gets this far
                //if there's an existing onload function
                if (typeof window.onload == 'function') {
                    //store it
                    existing = onload;
                    //add new onload handler
                    window.onload = function() {
                        //call existing onload function
                        existing();
                        //call generic onload function
                        doLoad();
                    };
                }
                else {
                    //setup onload function
                    window.onload = doLoad;
                }
            }
}
;

// Function which accepts functions to be run when dom is ready
_GMlib.onContentReady = function(f) { //(C)webreflection.blogspot.com
    var a,  b = navigator.userAgent, d = document, w = window, c = "__onContent__", e = "addEventListener", o = "opera", r = "readyState";
    w[c] = (function() {
        return function() {
            w[c] = function() {
            };
            f()
        }
    })();

    if (d[e])
        d[e]("DOMContentLoaded", w[c], false);
    if (/WebKit|Khtml/i.test(b) || (w[o] && (w[o].version ? parseInt(w[o].version()) < 9 : true))) // Applied change to support version number opera
        (function() {
            /loaded|complete/.test(d[r]) ? w[c]() : setTimeout(arguments.callee, 1)
        })();
    else
        if (/MSIE/i.test(b) && !_GMlib.browser.isMac) {
			document.write("<script id=__ie_onload defer src=javascript:void(0)><\/script>");
			var script = document.getElementById("__ie_onload");
			script.onreadystatechange = function() {
			  if (this.readyState == "complete") {
				__onContent__(); // call the onload handler
			  }
			};
		} // disabled for IE mac, doesn't seem to respond
        else {
            addOnLoadEvent(w[c])
        }
};





