﻿//devin onpay@msn.com
var dialog = {
    G : function(i){return document.getElementById(i);},
    contain : null,
    redirect : null,
    init : function(){
        var s = document.getElementsByTagName("a");
        var b = [];
        for(var i = 0; i < s.length; i++){
            var o = s[i];
            if(o.className.indexOf("dialog") != -1)
                o.onclick = function(){
                    var t = this.title || this.name || null ;
                    var a = this.href || this.alert;
                    var r = this.rel || false;
                    dialog.append(t,a,r,null);
                    this.blur();
                    return false;
                }
        }
    },
    alert : function(req){dialog.append(req.title,req.redirect,'',req.details);},
    append : function(caption, url, imageGroup,details){
        var isIe = /msie/i.test(navigator.userAgent);
        dialog.mask();
        if (!dialog.G("dialogAlert")){
            var contain = document.createElement("div");
            contain.id = "dialogAlert";
            contain.title = "";
            contain.className = "dialogs";
            dialog.contain = contain;
            contain.onmousedown = function (e){
                e = e || window.event;
                var srcElement = isIe ? e.srcElement : e.target;
                dialog.drag(e);
            };
            document.body.appendChild(contain);
        };
        if(details){
            dialog.redirect = url;
            var al = '<div class="dtitle"><label>'+caption+'</label><span onclick="dialog.remove();" title="点击关闭或按 esc 键">x</span></div><div class="alert" style="height:96px">'+details+'<a class="close" href="javascript:void(0)" onclick="dialog.remove();" title="点击关闭或按 esc 键">关闭</a></div>';
            contain.style.width = "300px";
            contain.style.height = "130px";
            contain.innerHTML = al;
        } else{
            var baseURL;
            if(url.indexOf("?")!==-1){ 
                baseURL = url.substr(0, url.indexOf("?"));
            }else{ 
                baseURL = url;
            }
            var urlString = /\.jpg$|\.jpeg$|\.png$|\.gif$|\.bmp$/;
            var urlType = baseURL.toLowerCase().match(urlString);
            var imgContent = [];
            var indexOfImage = 0;
            var imgPreloader = new Image();
            var pageHeight = document.documentElement.clientHeight;
            var pageWidth = document.documentElement.clientWidth;
            if(urlType == '.jpg' || urlType == '.jpeg' || urlType == '.png' || urlType == '.gif' || urlType == '.bmp'){
                 if(imageGroup){
                    var imgs = document.getElementsByTagName("a");
                    for(var i = 0; i < imgs.length; i++){
                        var o = imgs[i];
                        if(o.rel == imageGroup) {
                            imgContent.push({url:o.href,title:o.title});
                            if(o.href == url) indexOfImage = i;   
                        }
                    }
                    var s = new Array();
                    var tempImg = imgContent[indexOfImage];
                    imgPreloader.src =  imgContent[indexOfImage].url;
                    var tnext = (indexOfImage + 1) >= imgContent.length ? indexOfImage : indexOfImage + 1;
                    var tprev = (indexOfImage - 1) <= 0 ? 0 : indexOfImage - 1;
                    var tprevs = imgContent[tprev];
                    var tnexts = imgContent[tnext];
                    var prev = '{t:\''+tprevs.title+'\',u:\''+tprevs.url+'\',r:\''+imageGroup+'\'}';
                    var next = '{t:\''+tnexts.title+'\',u:\''+tnexts.url+'\',r:\''+imageGroup+'\'}';
                    imgPreloader.width = (imgPreloader.width >= pageWidth && imgPreloader.width >= imgPreloader.height) ? (pageWidth * 0.8) : imgPreloader.width ;
                    imgPreloader.height = (imgPreloader.height >= pageHeight && imgPreloader.height <= imgPreloader.width) ? (pageHeight * 0.8) : imgPreloader.height ;
                    var tempHeight = (imgPreloader.width + 16);
                    var tempWidth = (imgPreloader.height + 94);
                    if(tempHeight<100) tempHeight=200;
                    dialog.contain.style.width = tempHeight + "px";
                    dialog.contain.style.height = tempWidth + "px";
                    var pages = "";
                    var disp = "none";
                    var disps = "none";
                    if(indexOfImage >= (imgContent.length - 1)){disp = "";disps = "none";}
                    else if (indexOfImage <= 0){disp = "none";disps = "";}
                    else{disp = "";disps = "";}
                    pages = '<a href="javascript:void(0)" id="btnPrev" onclick="dialog.goNext('+prev+')" style="display:'+disp+';" title="上一张"><<</a><a href="javascript:void(0)" id="btnNext" onclick="dialog.goNext('+next+')" style="display:'+disps+';"  title="下一张">>></a>';
                    s.push('<div class="dtitle"><label>'+tempImg.title+'</label><span onclick="dialog.remove();" title="点击关闭或按 esc 键">x</span></div>');
                    s.push('<div class="dimg"><img src="'+tempImg.url+'" style="width:'+imgPreloader.width+'px;height:'+imgPreloader.height+'px;" /></div>');//caption, url, imageGroup
                    s.push('<div class="dpages"><div class="dtt">'+tempImg.title+'</div><div class="dzz"><font color="red">'+(indexOfImage+1)+'</font>/'+imgContent.length+'张 '+pages+'</div></div>');
                    dialog.contain.innerHTML = s.join("");
                 }
            } else{
                var queryString = url.replace(/^[^\?]+\??/,"");
                if(url.indexOf('iframe') != -1){
                    urlNoQuery = url.split('iframe');
                    this.content = "<iframe src=\""+ urlNoQuery[0] +"\" frameBorder=\"0\" marginHeight=\"0\" marginWidth=\"0\" width=\"100%\" height=\"100%\"></iframe>";
                    this._w =  parseInt(dialog.url("width",queryString));
                    this._h = parseInt(dialog.url("height",queryString));
                    this.left = (this.pw - this._w) / 2;
                    this.top = (this.ph - this._h) / 2;
                    this.title = caption;
                    var temp = '<div class="dtitle"><label>'+caption+'</label><span onclick="dialog.remove();" title="点击关闭或按 esc 键">x</span></div><div style="height:'+(this._h)+'px;" class="dcontent">'+this.content+'</div>';
                    dialog.contain.innerHTML = temp;
                    contain.style.width = this._w + "px";
                    contain.style.height = (this._h+22) + "px";
                }
            }
        }
        dialog.resize();
        document.onkeyup = function(e){ 	
	        if (e == null) keycode = event.keyCode; else keycode = e.which;
	        if(keycode == 27) dialog.remove();	
        };
        dialog.reload();
    },
    goNext : function(req){
        dialog.append(req.t,req.u,req.r);
    },
    resize : function(){
        if(dialog.contain){
            dialog.contain.style.top=(document.documentElement.scrollTop+(document.documentElement.clientHeight-dialog.contain.offsetHeight)/2)+"px";
            dialog.contain.style.left=(document.documentElement.scrollLeft+(document.documentElement.clientWidth-dialog.contain.offsetWidth)/2)+"px";
        }
    },
    reload : function(){
        window.onscroll = dialog.resize;
        window.onresize = dialog.resize;
        dialog.addEvent(dialog.resize);
    },
    url : function(p,url){
        var str = "[\?&]" + p + "=([^&]*)";
        var re = new RegExp(str,"gi");
        if(!re.test(url))return "";
        re.exec(url);
        return RegExp.$1;
    },
    drag : function(e){
	    var w = dialog.contain;
	    var relLeft = e.clientX-parseInt(w.style.left);
	    var relTop = e.clientY-parseInt(w.style.top);
	    document.onmousemove = function (e){
		    e = e || event;
		    if(w !=null){
		        if (e.clientX - relLeft <= 0) w.style.left = 0 + "px";
		        else if (e.clientX - relLeft >= document.documentElement.clientWidth - w.offsetWidth - 1)
			        w.style.left = (document.documentElement.clientWidth - w.offsetWidth - 1) + "px";
		        else
			        w.style.left = e.clientX - relLeft + "px";
		        if (e.clientY - relTop <= 1) w.style.top = 1 + "px";
		        else if (e.clientY - relTop >= document.documentElement.clientHeight - w.offsetHeight - 1)
			        w.style.top = (document.documentElement.clientHeight - w.offsetHeight - 1) + "px";
		        else
			        w.style.top = e.clientY - relTop + "px";
		    }
	    };
	    document.onselectstart = function (){return false;};
	    document.onmouseup = function (){w = null;document.onmouseup = document.onmousemove = document.onselectstart = null;};
    },
    mask : function(){
        this.pageWidth = dialog.page()[0];
        this.pageHeight = dialog.page()[1];
        this.windowWidth = dialog.page()[2];
        this.windowHeight = dialog.page()[3];
        if(dialog.browser() == "ie6"){
            var hs = document.createElement("iframe");
            hs.id = "dialogHideSelect";
            hs.style.cssText = "height:"+this.pageHeight+"px;width:"+this.windowWidth+"px;z-index:999;position:absolute;top:0;left:0;background:#fff;border:0;filter:alpha(opacity=0);";
            document.body.appendChild(hs);
        }
        var isIe = /msie/i.test(navigator.userAgent);
        var opacity = 0;
        if(isIe) opacity = dialog.opacity;
        else opacity = dialog.opacity / 100;
        if(!dialog.G("dialogMask")){
            var m = document.createElement("DIV");
            m.id = "dialogMask";
            m.onclick = function(){dialog.remove();};
            m.style.cssText = "height:"+this.pageHeight+"px;width:"+this.windowWidth+"px;position:absolute;top:0px;left:0px;background:"+dialog.mask.bgcolor+";filter:alpha(opacity="+opacity+");opacity:"+opacity+";z-index:9999;cursor:pointer;";
            document.body.appendChild(m);
        }
    },
    remove : function(){
        if(dialog.redirect) parent.location.href = dialog.redirect;
        if(dialog.browser() == "ie6"){
            var hs = dialog.G("dialogHideSelect");
            if(hs) hs.parentNode.removeChild(hs); 
        }
        var o = dialog.G("dialogMask");
        if(o) dialog.opacitys(o.id, 0, 6, 3);
        var v = dialog.G("dialogAlert");
        if(v) v.parentNode.removeChild(v); 
        document.onkeyup = "";
	    return true;
    },
    opacitys : function(id, end, step, time){
	    var o = document.getElementById(id);
	    if (!o) return;
	    var x = o.style;	
	    var Isie = navigator.appName.indexOf("Microsoft") > -1 ? true : false;
	    if (window["a" + id] != null) 
		    clearTimeout(window["a" + id]);
	    if (Isie) x = o.filters.alpha;
	    var opac = x.opacity;
	    if (!Isie) opac *= 100;
	    step = end < opac ? -1 * Math.abs(step) : Math.abs(step);
	    if (Math.abs(opac - end) <= Math.abs(step)) {
		    x.opacity = Isie ? end : end / 100;
		    window["a" + id] = null;
		    if (x.opacity == 0) o.parentNode.removeChild(o);
		    return;
	    }
	    if (opac + step < 0 && step < 0)
		    x.opacity = 0;
	    else if (opac + step > 100 && step > 0)
		    x.opacity = Isie ? 100 : 1;
	    else
		    x.opacity = Isie ? opac + step : (opac + step)/100;
	    window["a" + id] = window.setTimeout("dialog.opacitys(\""+ id +"\", \""+ end +"\", \""+ step +"\", \""+ time +"\");", time);
    },
    page : function(){
        var xScroll, yScroll; //
        var windowWidth, windowHeight ,pageWidth ,pageHeight;
        if (window.innerHeight && window.scrollMaxY) {xScroll = document.body.scrollWidth;yScroll = window.innerHeight + window.scrollMaxY;} 
        else if (document.body.scrollHeight > document.body.offsetHeight){xScroll = document.body.scrollWidth;yScroll = document.body.scrollHeight;} 
        else {xScroll = document.body.offsetWidth;yScroll = document.body.offsetHeight;} 
        if (self.innerHeight) {windowWidth = self.innerWidth;windowHeight = self.innerHeight;} 
        else if (document.documentElement && document.documentElement.clientHeight) {windowWidth = document.documentElement.clientWidth;windowHeight = document.documentElement.clientHeight;} 
        else if (document.body) {windowWidth = document.body.clientWidth;windowHeight = document.body.clientHeight;} 
        if(yScroll < windowHeight) pageHeight = windowHeight; else pageHeight = yScroll; 
        if(xScroll < windowWidth) pageWidth = windowWidth;else pageWidth = xScroll; 
        arrayPageSize = new Array(pageWidth,pageHeight,xScroll,yScroll);
        return arrayPageSize; 
    },
    addEvent : function(fun){
	    var oldonload = window.onload;
	    if (typeof window.onload != 'function') {window.onload = fun;}
	    else {window.onload = function() {oldonload();fun();}}
    },
    browser : function(){
        var nu = navigator.userAgent;
        if (nu.search(/msie 6.0/i) > -1)
	        return "ie6";
    }
}
dialog.opacity = 50; // 0~100
dialog.mask.bgcolor = "black";
dialog.addEvent(dialog.init);

