/*  Prototype JavaScript framework
 *  (c) 2005 Sam Stephenson <sam@conio.net>
 *  Prototype is freely distributable under the terms of an MIT-style license.
 *  For details, see the Prototype web site: http://prototype.conio.net/
/*--------------------------------------------------------------------------*/

//note: modified & stripped down version of prototype, to be used with moo.fx by mad4milk (http://moofx.mad4milk.net).

var Prototype = {
  Version: '1.4.0',
  ScriptFragment: '(?:<script.*?>)((\n|\r|.)*?)(?:<\/script>)',

  emptyFunction: function() {},
  K: function(x) {return x}
}

var Class = {
	create: function() {
		return function() {
			this.initialize.apply(this, arguments);
		}
	}
}

Object.extend = function(destination, source) {
	for (property in source) destination[property] = source[property];
	return destination;
}

Function.prototype.bind = function(object) {
	var __method = this;
	return function() {
		return __method.apply(object, arguments);
	}
}

Function.prototype.bindAsEventListener = function(object) {
var __method = this;
	return function(event) {
		__method.call(object, event || window.event);
	}
}

function $() {
	if (arguments.length == 1) return get$(arguments[0]);
	var elements = [];
	$c(arguments).each(function(el){
		elements.push(get$(el));
	});
	return elements;

	function get$(el){
		if (typeof el == 'string') el = document.getElementById(el);
		return el;
	}
}

Object.extend(String.prototype, {
  stripTags: function() {
    return this.replace(/<\/?[^>]+>/gi, '');
  },

  stripScripts: function() {
    return this.replace(new RegExp(Prototype.ScriptFragment, 'img'), '');
  },

  extractScripts: function() {
    var matchAll = new RegExp(Prototype.ScriptFragment, 'img');
    var matchOne = new RegExp(Prototype.ScriptFragment, 'im');
    return (this.match(matchAll) || []).map(function(scriptTag) {
      return (scriptTag.match(matchOne) || ['', ''])[1];
    });
  },

  evalScripts: function() {
    return this.extractScripts().map(eval);
  },

  escapeHTML: function() {
    var div = document.createElement('div');
    var text = document.createTextNode(this);
    div.appendChild(text);
    return div.innerHTML;
  },

  unescapeHTML: function() {
    var div = document.createElement('div');
    div.innerHTML = this.stripTags();
    return div.childNodes[0] ? div.childNodes[0].nodeValue : '';
  },

  toQueryParams: function() {
    var pairs = this.match(/^\??(.*)$/)[1].split('&');
    return pairs.inject({}, function(params, pairString) {
      var pair = pairString.split('=');
      params[pair[0]] = pair[1];
      return params;
    });
  },

  toArray: function() {
    return this.split('');
  },

  camelize: function() {
    var oStringList = this.split('-');
    if (oStringList.length == 1) return oStringList[0];

    var camelizedString = this.indexOf('-') == 0
      ? oStringList[0].charAt(0).toUpperCase() + oStringList[0].substring(1)
      : oStringList[0];

    for (var i = 1, len = oStringList.length; i < len; i++) {
      var s = oStringList[i];
      camelizedString += s.charAt(0).toUpperCase() + s.substring(1);
    }

    return camelizedString;
  },

  inspect: function() {
    return "'" + this.replace('\\', '\\\\').replace("'", '\\\'') + "'";
  },
  
  replaceAll : function(from, to) { 
		return this.replace(new RegExp(from, "g"), to); 
	}
});

if (!window.Element) var Element = new Object();

Object.extend(Element, {
	remove: function(element) {
		element = $(element);
		element.parentNode.removeChild(element);
	},

	update: function(element, html) {
    $(element).innerHTML = html.stripScripts();
    setTimeout(function() {html.evalScripts()}, 10);
  },
  
	hasClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var hasClass = false;
		element.className.split(' ').each(function(cn){
			if (cn == className) hasClass = true;
		});
		return hasClass;
	},

	addClassName: function(element, className) {
		element = $(element);
		Element.removeClassName(element, className);
		element.className += ' ' + className;
	},
  
	removeClassName: function(element, className) {
		element = $(element);
		if (!element) return;
		var newClassName = '';
		element.className.split(' ').each(function(cn, i){
			if (cn != className){
				if (i > 0) newClassName += ' ';
				newClassName += cn;
			}
		});
		element.className = newClassName;
	},

	cleanWhitespace: function(element) {
		element = $(element);
		$c(element.childNodes).each(function(node){
			if (node.nodeType == 3 && !/\S/.test(node.nodeValue)) Element.remove(node);
		});
	},

	find: function(element, what) {
		element = $(element)[what];
		while (element.nodeType != 1) element = element[what];
		return element;
	}
});

var Try = {
  these: function() {
    var returnValue;

    for (var i = 0; i < arguments.length; i++) {
      var lambda = arguments[i];
      try {
        returnValue = lambda();
        break;
      } catch (e) {}
    }

    return returnValue;
  }
}

/* seful array functions
Array.prototype.iterate = function(func){
	for(var i=0;i<this.length;i++) func(this[i], i);
}
if (!Array.prototype.each) Array.prototype.each = Array.prototype.iterate;
*/
function $c(array){
	var nArray = [];
	for (var i=0;i<array.length;i++) nArray.push(array[i]);
	return nArray;
}

String.prototype.parseQuery = String.prototype.toQueryParams;

var $break    = new Object();
var $continue = new Object();

var Enumerable = {
  each: function(iterator) {
    var index = 0;
    try {
      this._each(function(value) {
        try {
          iterator(value, index++);
        } catch (e) {
          if (e != $continue) throw e;
        }
      });
    } catch (e) {
      if (e != $break) throw e;
    }
  },

  include: function(object) {
    var found = false;
    this.each(function(value) {
      if (value == object) {
        found = true;
        throw $break;
      }
    });
    return found;
  }
}

Object.extend(Array.prototype, {
  _each: function(iterator) {
    for (var i = 0; i < this.length; i++)
      iterator(this[i]);
  }
});

/* Ajax Start*/
var Ajax = {
  getTransport: function() {
    return Try.these(
      function() {return new ActiveXObject('Msxml2.XMLHTTP')},
      function() {return new ActiveXObject('Microsoft.XMLHTTP')},
      function() {return new XMLHttpRequest()}
    ) || false;
  },

  activeRequestCount: 0
}

Ajax.Responders = {
  responders: [],

  _each: function(iterator) {
    this.responders._each(iterator);
  },

  register: function(responderToAdd) {
    if (!this.include(responderToAdd))
      this.responders.push(responderToAdd);
  },

  unregister: function(responderToRemove) {
    this.responders = this.responders.without(responderToRemove);
  },

  dispatch: function(callback, request, transport, json) {
    this.each(function(responder) {
      if (responder[callback] && typeof responder[callback] == 'function') {
        try {
          responder[callback].apply(responder, [request, transport, json]);
        } catch (e) {}
      }
    });
  }
};

Object.extend(Ajax.Responders, Enumerable);

Ajax.Responders.register({
  onCreate: function() {
    Ajax.activeRequestCount++;
  },

  onComplete: function() {
    Ajax.activeRequestCount--;
  }
});

Ajax.Base = function() {};
Ajax.Base.prototype = {
  setOptions: function(options) {
    this.options = {
      method:       'post',
      asynchronous: true,
      parameters:   ''
    }
    Object.extend(this.options, options || {});
  },

  responseIsSuccess: function() {
    return this.transport.status == undefined
        || this.transport.status == 0
        || (this.transport.status >= 200 && this.transport.status < 300);
  },

  responseIsFailure: function() {
    return !this.responseIsSuccess();
  }
}

Ajax.Request = Class.create();
Ajax.Request.Events =
  ['Uninitialized', 'Loading', 'Loaded', 'Interactive', 'Complete'];

Ajax.Request.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(url, options) {
    this.transport = Ajax.getTransport();
    this.setOptions(options);
    this.request(url);
  },

  request: function(url) {
    var parameters = this.options.parameters || '';
    if (parameters.length > 0) parameters += '&_=';

    try {
      this.url = url;
      if (this.options.method == 'get' && parameters.length > 0)
        this.url += (this.url.match(/\?/) ? '&' : '?') + parameters;

      Ajax.Responders.dispatch('onCreate', this, this.transport);

      this.transport.open(this.options.method, this.url,
        this.options.asynchronous);

      if (this.options.asynchronous) {
        this.transport.onreadystatechange = this.onStateChange.bind(this);
        setTimeout((function() {this.respondToReadyState(1)}).bind(this), 10);
      }

      this.setRequestHeaders();

      var body = this.options.postBody ? this.options.postBody : parameters;
      this.transport.send(this.options.method == 'post' ? body : null);

    } catch (e) {
      this.dispatchException(e);
    }
  },

  setRequestHeaders: function() {
    var requestHeaders =
      ['X-Requested-With', 'XMLHttpRequest',
       'X-Prototype-Version', Prototype.Version];

    if (this.options.method == 'post') {
      requestHeaders.push('Content-type',
        'application/x-www-form-urlencoded');

      /* Force "Connection: close" for Mozilla browsers to work around
       * a bug where XMLHttpReqeuest sends an incorrect Content-length
       * header. See Mozilla Bugzilla #246651.
       */
      if (this.transport.overrideMimeType)
        requestHeaders.push('Connection', 'close');
    }

    if (this.options.requestHeaders)
      requestHeaders.push.apply(requestHeaders, this.options.requestHeaders);

    for (var i = 0; i < requestHeaders.length; i += 2)
      this.transport.setRequestHeader(requestHeaders[i], requestHeaders[i+1]);
  },

  onStateChange: function() {
    var readyState = this.transport.readyState;
    if (readyState != 1)
      this.respondToReadyState(this.transport.readyState);
  },

  header: function(name) {
    try {
      return this.transport.getResponseHeader(name);
    } catch (e) {}
  },

  evalJSON: function() {
    try {
      return eval(this.header('X-JSON'));
    } catch (e) {}
  },

  evalResponse: function() {
    try {
      return eval(this.transport.responseText);
    } catch (e) {
      this.dispatchException(e);
    }
  },

  respondToReadyState: function(readyState) {
    var event = Ajax.Request.Events[readyState];
    var transport = this.transport, json = this.evalJSON();

    if (event == 'Complete') {
      try {
        (this.options['on' + this.transport.status]
         || this.options['on' + (this.responseIsSuccess() ? 'Success' : 'Failure')]
         || Prototype.emptyFunction)(transport, json);
      } catch (e) {
        this.dispatchException(e);
      }

      if ((this.header('Content-type') || '').match(/^text\/javascript/i))
        this.evalResponse();
    }

    try {
      (this.options['on' + event] || Prototype.emptyFunction)(transport, json);
      Ajax.Responders.dispatch('on' + event, this, transport, json);
    } catch (e) {
      this.dispatchException(e);
    }

    /* Avoid memory leak in MSIE: clean up the oncomplete event handler */
    if (event == 'Complete')
      this.transport.onreadystatechange = Prototype.emptyFunction;
  },

  dispatchException: function(exception) {
    (this.options.onException || Prototype.emptyFunction)(this, exception);
    Ajax.Responders.dispatch('onException', this, exception);
  },
  
  lostSession : function(msg){
  	alert(msg);
  }
});

Ajax.Updater = Class.create();

Object.extend(Object.extend(Ajax.Updater.prototype, Ajax.Request.prototype), {
  initialize: function(container, url, options) {
    this.containers = {
      success: container.success ? $(container.success) : $(container),
      failure: container.failure ? $(container.failure) :
        (container.success ? null : $(container))
    }

    this.transport = Ajax.getTransport();
    this.setOptions(options);

    var onComplete = this.options.onComplete || Prototype.emptyFunction;
    this.options.onComplete = (function(transport, object) {
      this.updateContent();
      onComplete(transport, object);
    }).bind(this);

    this.request(url);
  },

  updateContent: function() {
    var receiver = this.responseIsSuccess() ?
      this.containers.success : this.containers.failure;
    var response = this.transport.responseText;

    if (!this.options.evalScripts) response = response.stripScripts();

    if (receiver) {
      if (this.options.insertion) {
        new this.options.insertion(receiver, response);
      } else {
        Element.update(receiver, response);
      }
    }

    if (this.responseIsSuccess()) {
      if (this.onComplete)
        setTimeout(this.onComplete.bind(this), 10);
    }
  }
});

Ajax.PeriodicalUpdater = Class.create();
Ajax.PeriodicalUpdater.prototype = Object.extend(new Ajax.Base(), {
  initialize: function(container, url, options) {
    this.setOptions(options);
    this.onComplete = this.options.onComplete;

    this.frequency = (this.options.frequency || 2);
    this.decay = (this.options.decay || 1);

    this.updater = {};
    this.container = container;
    this.url = url;

    this.start();
  },

  start: function() {
    this.options.onComplete = this.updateComplete.bind(this);
    this.onTimerEvent();
  },

  stop: function() {
    this.updater.onComplete = undefined;
    clearTimeout(this.timer);
    (this.onComplete || Prototype.emptyFunction).apply(this, arguments);
  },

  updateComplete: function(request) {
    if (this.options.decay) {
      this.decay = (request.responseText == this.lastText ?
        this.decay * this.options.decay : 1);

      this.lastText = request.responseText;
    }
    this.timer = setTimeout(this.onTimerEvent.bind(this),
      this.decay * this.frequency * 1000);
  },

  onTimerEvent: function() {
    this.updater = new Ajax.Updater(this.container, this.url, this.options);
  }
});
/* Ajax END*/

/* User Define */
function ajaxSend(url,params,responseFunction) {
	var myAjax = new Ajax.Request(
		url, 
		{
			method: 'post', 
			parameters: params, 
			onComplete: responseFunction,
			asynchronous: true
		});
}


//default �ε�޼���
function loading_default(divNm,msg){
	eval(divNm).innerHTML="<p align='center'>"+msg+"</p>";
}

// *****  해쉬 맵 클래스 **** //
JHashMap = Class.create();
JHashMap.prototype = {
	keys:null,
	values:null,
	size:0,
	initialize : function () {
		this.keys=new Array();
		this.values=new Array();
	},
	put : function (key,value) {
		if(this.getKeyIndex(key)>=0){
			var idx=this.getKeyIndex(key);
			this.keys[idx]=key;
			this.values[idx]=value;
		}else{
			this.keys[this.size]=key;
			this.values[this.size]=value;
			this.size=this.size+1;
		}
		
	},
	get : function(key){
		if(this.size==0) return null;
		for(var i=0;i<this.keys.length;i++){
			if(this.keys[i]==key) return this.values[i];
		}
		return null;
	},
	getKeyIndex : function(key){
		if(this.size==0) return -1;
		for(var i=0;i<this.keys.length;i++){
			if(this.keys[i]==key) return i;
		}
		return -1;
	},
	getKeys : function(){
		return this.keys;
	},
	getValues : function(){
		return this.values;
	},
	remove : function(key){
		var rmIdx=this.getKeyIndex(key);
		if(rmIdx==-1)return;
		this.keys[rmIdx]=this.keys[this.keys.length-1];
		this.keys.length=this.keys.length-1;
		this.values[rmIdx]=this.values[this.values.length-1];
		this.values.length=this.values.length-1;
		this.size=this.size-1;
	}
};


/// *****  팝업  클래스  **** //

JPopup = Class.create();
JPopup.prototype = {
	oPopup   : null,  
	oDiv	 : null,  
	xWidth   :  250,
	yWidth   :  200,
	xOffset  :    0,
	yOffset  :    0,
	vFlag    : null,
	evtNode  : null,
	
	initialize : function (header) {
		this.menuItem = new Array();
		this.menuLink = new Array();
		this.header   = header;
		this.vFlag    = "hidden";
		this.oPopup   = window.createPopup();

	},
	putMenu : function (item,link) {
		this.menuItem.push(item);
		this.menuLink.push(link);
	},
	setDivClass : function (divClassName) {
		this.menuLink.push(link);
	},
	getMenu : function () {
		alert (this.menuItem.length);
	},
	getEventNode : function () {
		return this.evtNode;
	},
	
	evtMenu : function(eventV){
		var oNode = eventV.srcElement;
		this.evtNode = oNode;

		var htmlCode = "";
		var oDivX = eventV.clientX - eventV.offsetX  - 3;
		var oDivY = eventV.clientY - eventV.offsetY + oNode.clientHeight + 2;
		
		htmlCode ="<div style='overflow-y:auto;width"+this.xWidth+";height:"+this.yWidth+";"+"'><table width='100%' class='sm_title'>";
		
		// header 정보존 재시
		if (this.header != null && this.header != "" ){
			htmlCode += "<tr width='100%' bgcolor ='green' onClick='javascript : parent."+this.menuLink[i]+"()'>";
			htmlCode += "<td width='100%' align='left'> ▶ "+this.header+"</td>";
			htmlCode += "</tr>";
		}
		for (var i=0; i < this.menuItem.length; i++){
			htmlCode += "<tr width='100%' bgcolor ='yellow' style='cursor:hand'   onClick='javascript : parent."+this.menuLink[i]+"()'>";
			htmlCode += "<td width='100%' align='left'>"+this.menuItem[i]+"</td>";
			htmlCode += "</tr>";
		}
		htmlCode +="</table></div>";

		if (!this.oPopup.isOpen && this.vFlag == "hidden"){
			this.oPopup.document.body.innerHTML = htmlCode;
//			alert(this.oPopup.document.body.innerHTML);

			this.oPopup.show(oDivX + this.xOffset, oDivY+ this.yOffset, this.xWidth, this.yWidth,document.body);

//			this.oDiv.style.width = oNode.clientWidth;
		    this.vFlag = "visible";
		} else if (this.vFlag == "visible"){
			this.oPopup.hide();
		    this.vFlag = "hidden";
		}
	}
};


/// *****  팝업  메뉴 클래스  **** //

JPopupMenu = Class.create();
JPopupMenu.prototype = {
	header   : null,
	menuItem : null,
	menuLink : null,
	oPopup   : null,
	oDiv	 : null,
	xWidth   :  150,
	yWidth   :  100,
	xOffset  :    0,
	yOffset  :    0,
	vFlag    : null,
	oNode    : null,
	rowIndex : null,
	cellIndex: null,	
	evtNode  : null,

	oTrClass : null,
	oDivClass: null,
	oTableClass : null,
	
	initialize : function (header,x,y) {
		this.menuItem = new Array();
		this.menuLink = new Array();
		this.header   = header;
		this.vFlag    = "hidden";
		this.xWidth = x;
		this.yWidth = y;
		this.oPopup   = window.createPopup();
		this.oPopup.document.createStyleSheet('/gqas/html/css/gqas.css');
	},
	putMenu : function (item,link) {
		this.menuItem.push(item);
		this.menuLink.push(link);
	},
	setOffsetXY : function (x, y) {
		this.xOffset = x;
		this.yOffset = y;
	},
	setDivClass : function (divClassName) {
		this.menuLink.push(link);
	},
	getMenu : function () {
		alert (this.menuItem.length);
	},
	getRowIndex : function () {
		return this.rowIndex;
	},
	getCellIndex : function () {
		return this.cellIndex;
	},
	getNode : function () {
		return this.oNode;
	},
	getEventNode : function () {
		return this.evtNode;
	},
	evtMenu : function(eventV){

		var oNode = eventV.srcElement;
		this.evtNode = oNode;

		if (oNode.nodeName == 'TD'){
			this.rowIndex = oNode.parentElement.rowIndex;
			this.cellIndex = oNode.cellIndex;
			this.oNode = oNode;
		} else if (oNode.nodeName == 'INPUT') {
			return;
		
		}
		
		var htmlCode = "";

		var oDivX = eventV.clientX - eventV.offsetX - 3;
		var oDivY = eventV.clientY - eventV.offsetY + this.evtNode.clientHeight + 2;

		htmlCode  = "<div style='overflow-y:auto;width"+this.xWidth+";height:"+this.yWidth+";background-color:transparent;'>";
		htmlCode += "<table width='100%' border='0' cellpadding='0' cellspacing='0' class='sm_box'>";
		
		// header 정보존 재시
		if (this.header != null && this.header != "" ){
			htmlCode += "<tr class='sm_title' onClick='javascript : parent."+this.menuLink[i]+"'>";
			htmlCode += "  <td width='100%' align='left'><img src='/gqas/html/images/Bullet_t_sm.gif' >"+this.header+"</td>";
			htmlCode += "</tr>";
		}
		htmlCode += "<tr class='sm_title'>";
		htmlCode += "  <td width='100%' align='left' height='2'></td>";
		htmlCode += "</tr>";
		for (var i=0; i < this.menuItem.length; i++){
			htmlCode += "<tr style='cursor:hand' onClick='javascript : parent."+this.menuLink[i]+"'>";
			htmlCode += "  <td width='100%' class='sm_con'><img src='/gqas/html/images/Bullet_sm.gif' width='13' height='5' align='absmiddle'>"+this.menuItem[i]+"</td>";
			htmlCode += "</tr>";
		}
		htmlCode +="</table></div>";
		


		if (!this.oPopup.isOpen ){
			this.oPopup.document.body.innerHTML = htmlCode;
//			alert(this.oPopup.document.body.innerHTML);

			this.oPopup.hide();

			this.oPopup.show(oDivX + this.xOffset, oDivY+ this.yOffset, this.xWidth, this.yWidth,document.body);

//			this.oDiv.style.width = oNode.clientWidth;
		    this.vFlag = "visible";
		} else if (this.vFlag == "visible"){
			this.oPopup.hide();
		    this.vFlag = "hidden";
		}
	}
};
function mytest(){
	alert("dddd");
}


function sendRecommend(){
	
	var url = "/gqas/jsp/comm/combo.jsp";		
	var reqParam="";
	reqParam += "cmd="+"CARS";

	ajaxSend(url,reqParam,showRecommend);
}
	
function showRecommend(res) {
	//alert (res.responseText);
	var oPopup   = window.createPopup();
	oPopup.document.body.innerHTML = res.responseText;
	oPopup.show(10,10,100,300,document.body);
		

//	evalScriptById("functest");

/*
	$('recommendArea').innerHTML=res.responseText;
	evalScriptById("recommendScript");
	
	var links = document.getElementsByName("themelink");
	for (i = 0;i < links.length;i++) {
		if (homeSThemeId == links[i].name) {
			links[i].style.display = "none";
		} else {
			links[i].style.display = "block";
		}
	}
	*/
	
}



