/** LogConsole (v 0.2) 
*   logConsole will always execute, until user close the logConsole
*   when logConsole was closed, all error will pass to browser
*   debug mode control the logConsole is visible or not
*
*   var logMask;
*   var log;
*   
*   function setLog(msg,type){
*       log.write(msg,type);
*   } 
*
*   //when drag and drop over a iframe, pls use logMask
*   function setLogConsole(){
*       logMask=new LogMask('logMask');
*       log=new LogConsole('logger','image_path','debbug_mode',logMask);
*   }
*
**/

var LogConsole = Class.create();
LogConsole.prototype = {
	initialize:function(id,img_path,path,start){
	    this.id=id;
	    this.img_path=img_path + '/__img/pro//';
	    this.path= path=='' ? '' : path;
	    this.button_path=this.img_path + 'buttons/';
        this.start = (start == true) ? start : false;
        this.pause = false;
        this.status = 'max';
        this.oHeight=0;
        this.oWidth=0;
        this.oX=0;
        this.oY=0;
        //width when it is monimize
        this.minWidth="120px";

	    this.type=new Array('debug','ajax','sql','resp','fatal','err');
	    this.consoleDiv = '\
        <div id="' + this.id + '_logConsole" class="logConsole">\
            <div id="' + this.id + '_title" class="title" onselectstart="return false;">\
                <span class="title_text">Log Console</span>\
                <img src="' + this.button_path + 'close_up.gif" id="' + this.id + '_close" class="title_close" />\
                <img src="' + this.button_path + 'min_up.gif" id="' + this.id + '_hide" class="title_hide" />\
            </div>\
            <div id="' + this.id + '_body" class="body">\
                <div id="' + this.id + '_content" class="content"></div>\
                <div id="' + this.id + '_option" class="option" onselectstart="return false;">\
                    <input type="button" id="' + this.id + '_clear" class="button" value="Clear" /><input type="button" id="' + this.id + '_resume" class="button" value="Pause" /><input type="button" id="' + this.id + '_exportRec" class="button" value="Export" />\
                </div>\
            </div>\
        </div>';  

        this.create();
        this.enable(this.start);
        
        this.eventCloseClick=this.close.bindAsEventListener(this);
        Event.observe(this.id + '_close', 'click', this.eventCloseClick);
        this.eventHideClick=this.hide.bindAsEventListener(this);
		Event.observe(this.id + '_hide', 'click', this.eventHideClick);
		this.eventClearClick=this.clear.bindAsEventListener(this);
		Event.observe(this.id + '_clear', 'click', this.eventClearClick);
        this.eventResumeClick=this.resume.bindAsEventListener(this);
		Event.observe(this.id + '_resume', 'click', this.eventResumeClick);		
		this.eventExportRecClick=this.exportRec.bindAsEventListener(this);
		Event.observe(this.id + '_exportRec', 'click', this.eventExportRecClick);
    },
    
    create:function(){
        var body = document.getElementsByTagName("body")[0];
		new Insertion.Bottom(body, this.consoleDiv);
	
		this.dragdrop=new Draggable(this.id + "_logConsole",{
		    handle:this.id + '_title',
		    zindex:'1000',
		    starteffect:function(){logMask.enable(true)},
            endeffect:function(){logMask.enable(false)}}
        );

        this.resize=new Resizeable(this.id + "_logConsole",{
            minWidth:'280',
            minHeight:'100',
            zindex:'1000',
            snap:'50',
            starteffect:function(){logMask.enable(true)},
            endeffect:function(){logMask.enable(false)}}
        );  

			//為所有的type插入checkbox及定義onmousedown event
			for (var i=0;i<this.type.length;i++){
		    new Insertion.Bottom($(this.id + '_option'), '<input type="checkbox" id="' + this.id + '_check_' + this.type[i] + '" value="true" checked="checked" />' + this.type[i]);
		    Event.observe(this.id + '_check_' + this.type[i], 'click', this.hideRec.bindAsEventListener(this,this.type[i]));
        }
    },
    
	enable:function(val){
		if(val){
		    Element.show(this.id + "_logConsole");
        } else {
            Element.hide(this.id + "_logConsole");
        }
	},
	
	write:function(msg,type){ 
	    msg=(typeof(msg)!='undefined') ? msg : '';
	    type=(typeof(type)!='undefined') ? type : this.type[0];
	    if (this.start){
            if (this.inArray(type)){
                if ((!this.pause) && ($F(this.id + '_check_' + type) == "true")){
                    new Insertion.Bottom(this.id + '_content', '<div class="logRec logRec_' + type + '"><img src="' + this.img_path + 'icons/' + type + '.png" class="logType" /><div class="logMsg logMsg_' + type + '">' + this.jshtmlspecialchars(msg) + '</div><div class="clear"></div></div>');
                    this.setScroll();
                }
            } else {
                alert("找不到 " + type + " 的log type");
            }
            msg=null;
        }
    },
    
    hideRec:function(e,type){
	    $A(document.getElementsByClassName("logRec_" + type)).each(
	        function(i){
	    	    Element.toggle(i);
	        }
        );	
	},

	close:function(e){
	    $(this.id + '_content').innerHTML ="";
        this.start=false;
        this.enable(this.start);
        this.dragdrop.destroy();
        this.resize.destroy();

        Event.stopObserving(this.id + '_close', 'click', this.eventCloseClick);
        Event.stopObserving(this.id + '_hide', 'click', this.eventHideClick);
		Event.stopObserving(this.id + '_clear', 'click', this.eventClearClick);
		Event.stopObserving(this.id + '_resume', 'click', this.eventResumeClick);		
		Event.stopObserving(this.id + '_exportRec', 'click', this.eventExportRecClick);
        Event.stop(e);
	},
	
	hide:function(e){
	    Element.toggle($(this.id + '_body')); 
	    if (this.status=='max'){
	        //存起原有資料
	        this.oHeight=Element.getStyle(this.id + '_logConsole','height');
	        this.oWidth=Element.getStyle(this.id + '_logConsole','width');
	        this.oX=Element.getStyle(this.id + '_logConsole','left');
	        this.oY=Element.getStyle(this.id + '_logConsole','top');
	        
	        //設為minValue
	        Element.setStyle(this.id + '_logConsole',{height:this.getMinHeight()});
	        Element.setStyle(this.id + '_logConsole',{width:this.getMinWidth()});
	        //改變position至右下角(必須把left,top設為auto後,right,bottom才會生效)
	        Element.setStyle(this.id + '_logConsole',{left:'auto'});
	        Element.setStyle(this.id + '_logConsole',{right:'0px'});
	        Element.setStyle(this.id + '_logConsole',{top:'auto'});
	        Element.setStyle(this.id + '_logConsole',{bottom:'0px'});
	        $(this.id + '_hide').src = this.button_path + "max_up.gif";
	        this.status='min';
        } else if (this.status=='min'){
            //如縮小後被移動,於放大時會返回新位置
            if ((Element.getStyle(this.id + '_logConsole','left')==null) && (Element.getStyle(this.id + '_logConsole','top')==null)){
                Element.setStyle(this.id + '_logConsole',{left:this.oX});
	            Element.setStyle(this.id + '_logConsole',{top:this.oY});
            }
            Element.setStyle(this.id + '_logConsole',{height:this.oHeight});
            Element.setStyle(this.id + '_logConsole',{width:this.oWidth});
    
            $(this.id + '_hide').src = this.button_path + "min_up.gif";
            this.setScroll();
            this.status='max';
        }
        Event.stop(e);
	},
    
	getMinHeight:function(){
	    //把高度設為title的高度
        var h1=Element.getStyle(this.id + '_title','height');
	    var h2=Element.getStyle(this.id + '_title','padding-top');
	    var h3=Element.getStyle(this.id + '_title','padding-bottom');
	    return parseInt(h1.substr(0,h1.length-2)) + parseInt(h2.substr(0,h2.length-2)) + parseInt(h3.substr(0,h3.length-2)) + 'px';
    },
    
    getMinWidth:function(){
        return this.minWidth;
    },
   
	clear:function(e){
        $(this.id + '_content').innerHTML ="";
    },
    
    resume:function(e){
        this.pause=this.pause?false:true;
        $(this.id + '_resume').value = this.pause? "Resume" : "Pause";
    },

    exportRec:function(e){
        var popup = window.open("", this.id + "_popup", "toolbar,menubar,status,scrollbars,resizable,width=800,height=500");
        var rec=$(this.id + '_content').getElementsByClassName('logMsg');
        var counter=rec.length;
        for (var j=0;j<this.type.length;j++){
            //add ";" if this is a sql
            if ((this.type[j]=='sql') && ($(this.id + '_check_' + this.type[j]).checked)){
                for(var i=0;i<counter;i++){
                    if (rec[i].hasClassName('logMsg_sql')){
                        rec[i].innerHTML+=';';
                    }
                }
            }
            //empty the specific type of content if the checkbox haven't checked
            for(var i=0;i<counter;i++){
                if ((!$(this.id + '_check_' + this.type[j]).checked) && (rec[i].hasClassName('logMsg_' + this.type[j]))){
                    rec[i].innerHTML='';
                }
            }
        }
        
        var code=new Array();
        code.push('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">');
        code.push('<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="zh-TW" lang="zh-TW">');
        code.push('<head>');
        code.push('<meta http-equiv="content-type" content="text/html; charset=utf-8" />');
        code.push('<meta http-equiv="imagetoolbar" content="no" />');
        code.push('<link rel="stylesheet" href="' + this.path + '/_addOn/dp.SyntaxHighlighter151/Styles/SyntaxHighlighter.css"  type="text/css" media="all"/>');
        code.push('<script>');
        code.push('function changeFormat(obj){');
        code.push(' document.body.removeChild(document.getElementsByTagName("DIV")[0]);');
        code.push(' document.getElementById("code").className=obj.options[obj.selectedIndex].value;');
        code.push(' dp.SyntaxHighlighter.HighlightAll("code");');
        code.push('}');
        code.push('</script>');
        code.push('</head>');
        code.push('<body>');
        code.push('Highlight format : <select onchange="changeFormat(this);"><option value="Sql">SQL</option><option value="Xml">XML</option><option value="JScript">Javascript</option></select>');
        code.push('<textarea name="code" id="code" class="sql" rows="15" cols="100">');
        for(var i=0;i<counter;i++){
            if (rec[i].innerHTML!=''){
                code.push(rec[i].innerHTML);
            }
        }
        code.push('</textarea>');
        code.push('<script type="text/javascript">');
        code.push('function dhtmlLoadScript(URL){var e = document.createElement("script");e.src=URL;e.type="text/javascript";document.getElementsByTagName("head")[0].appendChild(e);}');
        code.push('onload=function(){');
        code.push('dhtmlLoadScript("' + this.path + '/_addOn/dp.SyntaxHighlighter151/Scripts/shCore.js");');
        code.push('dhtmlLoadScript("' + this.path + '/_addOn/dp.SyntaxHighlighter151/Scripts/shBrushSql.js");');
        code.push('dhtmlLoadScript("' + this.path + '/_addOn/dp.SyntaxHighlighter151/Scripts/shBrushXml.js");');
        code.push('dhtmlLoadScript("' + this.path + '/_addOn/dp.SyntaxHighlighter151/Scripts/shBrushJScript.js");');
        code.push('var interval = setInterval(function(){if(typeof(dp)!="undefinded"){dp.SyntaxHighlighter.HighlightAll(\'code\');clearInterval(interval);}},200);');
        code.push('}');
        code.push('</script></body></html>');
        popup.document.open();
        popup.document.write(code.join("\r\n"));
        code=null;
        popup.document.close();
    },

    setScroll:function(){
        var obj=$(this.id + '_content');
        obj.scrollTop = obj.scrollHeight;
    },
    
    inArray:function(val){
        for (var i=0; i < this.type.length; i++) {
            if (this.type[i] === val) {
                return true;         
            }     
        }     
        return false;
    },
    
    //for client side fatal error only
    errHandler:function(message,url,line,selfObj){
        var msg="Msg: " + message + "<br />Url: " + url + "<br />Line: " + line;
        selfObj.write(msg,'fatal');
    },
    
	jshtmlspecialchars:function(text) {
		var textneu = text.replace(/\</g,"&lt;");
		textneu = textneu.replace(/\>/g,"&gt;");
		textneu = textneu.replace(/\\r\n/g,"<br>");
		textneu = textneu.replace(/\\n/g,"<br>");
		textneu = textneu.replace(/\\r/g,"<br>");
		return(textneu);
	}	
};

var LogMask = Class.create();
LogMask.prototype = {
	initialize:function(id){
	    this.id=id;
        this.status=false;
	    this.div = '<div id="' + this.id + '" class="logMask"></div>';  
	    this.bodyID=this.getBodyID();

		var body = document.getElementsByTagName("body")[0];
		new Insertion.Bottom(body, this.div);
    },
    enable:function(val){
        if (this.status!=val){
            this.status=val;
            var i=val? 'block' : 'none';
            Element.setStyle(this.id,{display:i});
        }
	},
	getBodyID:function(){
    	var id=document.getElementsByTagName("body")[0].id;
    	if (id==''){
    	    alert('Please create an ID for body element');
        } else {
            return id;    
        }
    }
};    

