var JSUtil = Class.create( {
    initialize: function() {

		this.lastWindow = null;
        ua = navigator.userAgent;
        this.isMSIE = (navigator.appName == "Microsoft Internet Explorer");
        this.isMSIE5 = this.isMSIE && (ua.indexOf('MSIE 5') != -1);
        this.isMSIE5_0 = this.isMSIE && (ua.indexOf('MSIE 5.0') != -1);
        this.isMSIE7 = this.isMSIE && (ua.indexOf('MSIE 7') != -1);
		this.isMSIE8 = this.isMSIE && (ua.indexOf("MSIE 8") != -1);
        this.isGecko = ua.indexOf('Gecko') != -1; // Will also be true on Safari
        this.isSafari = ua.indexOf('Safari') != -1;
        this.isOpera = window['opera'] && opera.buildNumber ? true : false;
        this.isMac = ua.indexOf('Mac') != -1;
        this.isNS7 = ua.indexOf('Netscape/7') != -1;
        this.isNS71 = ua.indexOf('Netscape/7.1') != -1;
    
        // Fake MSIE on Opera and if Opera fakes IE, Gecko or Safari cancel those
        if (this.isOpera) {
                this.isMSIE = true;
                this.isGecko = false;
                this.isSafari =  false;
        }
    
        this.isIE = this.isMSIE;
        this.isRealIE = this.isMSIE && !this.isOpera;    
	},

	/**
    /* ÆË¾÷ ¶ç¿ì±â
    **/
    popWin: function(url, params, args) {
        var width, height, x, y, scrollbars, resizable, modal;
        if( !url ) { alert("URL does not exist."); return; }
        
        url = url + "?" + params;        
        width = (args && args.width) ? parseInt(args.width):320;
        height = (args && args.height) ? parseInt(args.height):320;
        modal = (args && args.modal) ? modal:"no";
        x=(args && args.x)?args.x:(screen.availWidth-width)/2;
        y=(args && args.y)?args.y:(screen.availHeight-height)/2;
        resizable = (args && args.resizable) ? args.resizable : "no";
        scrollbars = (args && args.scrollbars) ? args.scrollbars : "yes";
		name = (args && args.name) ? args.name : "Popup" + new Date().getTime();

        // Add to height in M$ due to SP2 WHY DON'T YOU GUYS IMPLEMENT innerWidth of windows!!
        if ( !this.isIE ) height += 25;

        //IEÀÏ °æ¿ì ¸ð´ÞÃ¢ ¶Ù¿î´Ù
        if( this.isRealIE && modal=="yes") {
            features = "resizable:" + resizable + ";scroll:" + scrollbars + ";status:no;center:yes;help:no;dialogWidth:" + width + "px;dialogHeight:" + height + "px;";
            window.showModalDialog(url, window, features);
        }else {

            if (this.isGecko && this.isMac)
                modal = "no";

            if( this.lastWindow != null ) {
                try { this.lastWindow.close(); this.lastWindow=null; } catch (e){}
            }

            win = window.open(url, name, "top=" + y + ",left=" + x + ",scrollbars=" + scrollbars + ",dialog=" + modal + ",minimizable=" + resizable + ",modal=" + modal + ",width=" + width + ",height=" + height + ",resizable=" + resizable + ",modal=" + modal);
            if (win == null) {
                alert("ÆË¾÷»ý¼º¿¡ ½ÇÆÐÇÏ¿´½À´Ï´Ù.");
                return;
            }

            if( this.lastWindow == null ) {
                try { this.lastWindow = win; } catch (e) {}
            }
        }

    },

	resizeImg: function( w, h, newW, newH ) {
		
		var tx, ty;
		if( newW && newH ) {
			if( w > newW || h > newH ) {
				aa = h/w;
				bb = newH/newW;

				if( aa <= bb ) {
					tx = newW;
					ty = Math.floor((h/w)*newW);
				} else {
					tx = Math.floor((w/h)*newH);
					ty = newH;
				}
			} else {
				tx = w;
				ty = h;
			}
		} else {
			var standard = (w>h)?w:h; 
			var rate = (100*newW)/standard; 
			tx = Math.floor(w*(rate/100)); 
			ty = Math.floor(h*(rate/100)); 
		}
		
		return [ tx, ty ];
	},

	prevImage: function(objFile, previewer, width, height) {

		if(!/(\.gif|\.jpg|\.jpeg|\.png)$/i.test(objFile.value.toLowerCase())) { alert("ÀÌ¹ÌÁö Çü½ÄÀÇ ÆÄÀÏÀ» ¼±ÅÃÇÏ½Ê½Ã¿À"); return; }

		// ºê¶ó¿ìÀú ±¸ºÐ
		if (this.isMSIE7) {    // ie 7 ÀÌ¸é

			previewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='" + objFile.value + "',sizingMethod=image)";
			var w = previewer.offsetWidth;
			var h = previewer.offsetHeight;
			
			var size = this.resizeImg(w, h, width, height);

			previewer.style.width = size[0]+'px';
			previewer.style.height = size[1] + 'px';

			previewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='file://" + String(objFile.value) +"', sizingMethod='scale')";
			/* 
			Á¦¾îÆÇ > ÀÎÅÍ³Ý ¿É¼Ç > º¸¾È > »ç¿ëÀÚ ÁöÁ¤ ¼öÁØ > ±âÅ¸ > ÆÄÀÏÀ» ¼­¹ö¿¡ ¾÷·ÎµåÇÒ ¶§ ·ÎÄÃ µð·ºÅÍ¸® °æ·Î Æ÷ÇÔ : »ç¿ë
			¼³Á¤ÇÑ °æ¿ì¿¡´Â ¾Æ·¡ÀÇ else if ºÎºÐÀ» À§ÀÇ ie 7 Á¶°ÇºÎ¿¡ OR Á¶°ÇÀ¸·Î Æ÷ÇÔ½ÃÄÑÁÖ±â¸¸ ÇÏ¸é µÈ´Ù. 
			*/
		} else if(this.isMSIE8) { // IE 8 ÀÌ¸é
			// objFile.Value °ªÀÌ 'C:\fakepath\ÆÄÀÏ°æ·Î' ÀÌ¹Ç·Î Å¬¸³º¸µå¸¦ ÀÌ¿ëÇÑ Æí¹ýÀ» ¾´´Ù.
			// Å¬¸³º¸µå ¿¢¼¼½º Çã¿ë¿©ºÎ¸¦ °è¼Ó ¹°¾îº¸´Âµ¥, ±ÍÂúÁö ¾Ê°Ô ¾²·Á¸é
			// Á¦¾îÆÇ > ÀÎÅÍ³Ý ¿É¼Ç > º¸¾È > »ç¿ëÀÚ ÁöÁ¤ ¼öÁØ > ½ºÅ©¸³ÆÃ > ÇÁ·Î±×·¥ Å¬¸³º¸µå ¾×¼¼½º Çã¿ë : »ç¿ë
			objFile.activate();
			document.execCommand('Copy');  
			previewer.style.filter = "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='file://" + String(window.clipboardData.getData('Text')) +"', sizingMethod='scale')";

		} else {    // ie 7 ÀÌ ¾Æ´Ñ ºê¶ó¿ìÀúÀÌ¸é
			previewer.innerHTML = "";
			var W = previewer.offsetWidth;
			var H = previewer.offsetHeight;
			//var tmpImage = new Image();
			var tmpImage = document.createElement( 'img' );
			previewer.appendChild(tmpImage);

			tmpImage.onerror = function () {
				//alert("ÀÌ¹ÌÁö ¹Ì¸®º¸±â »ý¼ºÁß ¿À·ù¹ß»ý.");   // ¿À·ù¹ß»ýÀ» ¾Ë¸®°í½ÍÀ¸¸é ÀÌ ÁÙ ¸Ç ¾ÕÀÇ ÁÖ¼® ÇØÁ¦
				return previewer.innerHTML = "";
			}

			tmpImage.onload = function () {
				if (this.width > W) {
					this.height = this.height / (this.width / W);
					this.width = W;
				}
				if (this.height > H) {
					this.width = this.width / (this.height / H);
					this.height = H;
				}
			}

			if (window.navigator.userAgent.indexOf("Firefox/3") != -1) {    // firefox3 ÀÌ¸é
				var picData = objFile.files.item(0).getAsDataURL();
				tmpImage.src = 'data:' + picData;
				tmpImage.writeAttribute("title", "ImageSize: "+ objFile.files.item(0).fileSize +" byte");
			} else {
				tmpImage.src = "file://" + objFile.value;
			}
		}
	}
});

/**
/* XML TO JSON
**/
// JavaScript Document
var XMLObjectifier = Class.create ({
    initialize: function() {},
    xmlToJSON: function(xdoc) {
        try {
            if(!xdoc){ return null; }
            var tmpObj = {};
            //tmpObj.typeOf = "JSXBObject";
            
            var xroot = (xdoc.nodeType == 9)?xdoc.documentElement:xdoc;
            
            if(xdoc.nodeType == 3 || xdoc.nodeType == 4) {
                    return xdoc.nodeValue;
            }			
            //Set Object Nodes
            function setObjects(obj, node) {
                var elemName;	//Element name
                var cnode;	//Current Node
                var tObj;	//New subnode
                var cName = "";
                if(!node) { return null; }
                if(!node.hasChildNodes()) { return null; }
                var nodeCount = node.childNodes.length - 1;	
                //Set node attributes if any
                
                if(node.attributes.length > 0) {
                        setAttributes(obj, node);
                }
                //Process child nodes
                obj._children = [];
                obj.Text = "";
                var n = 0;
                do { //Order is irrelevant (speed-up)
                    cnode = node.childNodes[n];
                    switch(cnode.nodeType) {
                        case 1: //Node
                        //SOAP XML FIX to remove namespaces (i.e. soapenv:)
                        elemName = (cnode.localName)?cnode.localName:cnode.baseName;
                        elemName = formatName(elemName);
                        if(cName != elemName) { obj._children.push(elemName); }
                            //Create sub elemns array
                            if(!obj[elemName]) {
                                    obj[elemName] = []; //Create Collection
                            }
                            tObj = {};
                            obj[elemName].push(tObj);
                            if(cnode.attributes.length > 0) {
                                    setAttributes(tObj, cnode);
                            }
                            //Set Helper functions (contains, indexOf, sort, etc);
                            if(!obj[elemName].contains) {
                                    setHelpers(obj[elemName]);
                            }	
                        cName = elemName;
                        if(cnode.hasChildNodes()) {
                                setObjects(tObj, cnode); //Recursive Call
                        }
                        break;
                        case 3: //Text Value
                        obj.Text += trim(cnode.nodeValue);
                        break;
                        case 4: //CDATA
                        obj.Text += (cnode.text)?trim(cnode.text):trim(cnode.nodeValue);
                        break;
                    }
                } while(n++ < nodeCount);
            }
            //Set collections
            function setHelpers(grpObj) {
                //Selects a node withing array where attribute = value
                grpObj.getNodeByAttribute = function(attr, obj) {
                    if(this.length > 0) {
                        var cNode;
                        var maxLen = this.length -1;
                        try {
                            do {
                                cNode = this[maxLen];
                                if(cNode[attr] == obj) {
                                        return cNode;
                                }
                            } while(maxLen--);
                        } catch(e) {return false;}
                        return false;
                    }
                }
                    
                grpObj.contains = function(attr, obj) {
                    if(this.length > 0) {
                        var maxLen = this.length -1;
                        try {
                            do {
                                if(this[maxLen][attr] == obj) {
                                    return true;
                                }
                            } while(maxLen--);
                        } catch(e) {return false;}
                        return false;
                    }
                }
                
                grpObj.indexOf = function(attr, obj) {
                    var pos = -1;
                    if(this.length > 0) {
                        var maxLen = this.length -1;
                        try {
                            do {
                                if(this[maxLen][attr] == obj) {
                                    pos = maxLen;
                                }
                            } while(maxLen--);
                        } catch(e) {return -1;}
                        return pos;
                    }
                }
                
                grpObj.SortByAttribute = function(col, dir) {
                    if(this.length) {				
                        function getValue(pair, idx) {
                            var out = pair[idx];
                            out = (isNumeric(out))?parseFloat(out):out;
                            return out;
                        }
                        function sortFn(a, b) {
                            var res = 0;
                            var tA, tB;						
                            tA = getValue(a, col);
                            tB = getValue(b, col);
                            if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
                            if(dir) {
                                    res = (dir.toUpperCase() == "DESC")?(0 - res):res;
                            }
                            return res;
                        }
                        this.sort(sortFn);
                    }
                }
                
                grpObj.SortByValue = function(dir) {
                    if(this.length) {
                        function getValue(pair) {
                            var out = pair.Text;
                            out = (isNumeric(out))?parseFloat(out):out;
                            return out;
                        }
                        function sortFn(a, b) {
                            var res = 0;
                            var tA, tB;
                            tA = getValue(a);
                            tB = getValue(b);
                            if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
                            if(dir) {
                                    res = (dir.toUpperCase() == "DESC")?(0 - res):res;
                            }
                            return res;
                        }
                        this.sort(sortFn);
                    }
                }
                
                grpObj.SortByNode = function(node, dir) {
                    if(this.length) {
                        function getValue(pair, node) {
                            var out = pair[node][0].Text;
                            out = (isNumeric(out))?parseFloat(out):out;
                            return out;
                        }
                        function sortFn(a, b) {
                            var res = 0;
                            var tA, tB;
                            tA = getValue(a, node);
                            tB = getValue(b, node);
                            if(tA < tB) { res = -1;	} else if(tB < tA) { res = 1; }
                            if(dir) {
                                res = (dir.toUpperCase() == "DESC")?(0 - res):res;
                            }
                            return res;
                        }
                        this.sort(sortFn);
                    }
                }
            }
            //Set Attributes of an object
            function setAttributes(obj, node) {
                if(node.attributes.length > 0) {
                    var a = node.attributes.length-1;
                    var attName;
                    obj._attributes = [];
                    do { //Order is irrelevant (speed-up)
                        attName = String(formatName(node.attributes[a].name));
                        obj._attributes.push(attName);				
                        obj[attName] = trim(node.attributes[a].value);
                    } while(a--);
                }
            }
            //Alters attribute and collection names to comply with JS
            function formatName(name) {
                var regEx = /-/g;
                var tName = String(name).replace(regEx,"_");
                return tName;
            }
            //Is Numeric check
            function isNumeric(s) {
                var testStr = "";
                if(s && typeof s == "string") { testStr = s; }
                var pattern = /^((-)?([0-9]*)((\.{0,1})([0-9]+))?$)/;
                return pattern.test(testStr);
            }
            //Trim function
            function trim(s) {
                return s.replace(/^\s+|\s+$/gm,'');
            }
            //RUN
            setObjects(tmpObj, xroot);
            //Clean-up memmory
            xdoc = null;
            xroot = null;
            return tmpObj;	
        } catch(e) {
            return null;	
        }	
    },

    //Converts Text to XML DOM
    textToXML: function(strXML) {
        try {
            var xmlDoc = (document.all)?new ActiveXObject("Microsoft.XMLDOM"):new DOMParser();
            xmlDoc.async = false;
        } catch(e) {throw new Error("XML Parser could not be instantiated");}
        var out;
        try {
            if(document.all) {
                out = (xmlDoc.loadXML(strXML))?xmlDoc:false;
            } else {		
                out = xmlDoc.parseFromString(strXML, "text/xml");
            }
        } catch(e) { throw new Error("Error parsing XML string"); }
        return out;
    }	
});

var xml2json = new XMLObjectifier();
var jsUtil = new JSUtil();
