function dummy() {};

function LTrim(str)
{
    var whitespace = new String(" \t\n\r");
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(0)) != -1)
    {
        var j=0, i = s.length;
        while (j < i && whitespace.indexOf(s.charAt(j)) != -1)
            j++;
        s = s.substring(j, i);
    }
    return s;
}

function RTrim(str)
{
    var whitespace = new String(" \t\n\r");
    var s = new String(str);

    if (whitespace.indexOf(s.charAt(s.length-1)) != -1)
    {
        var i = s.length - 1;
        while (i >= 0 && whitespace.indexOf(s.charAt(i)) != -1)
            i--;
        s = s.substring(0, i+1);
    }
    return s;
}

function Trim(str)
{
    return RTrim(LTrim(str));
}

InputFieldControl = Class.create();
InputFieldControl.prototype =
{
    initialize: function(showed,checkFunc,obj)
    {
        this.showed = showed;
        this.objAppearing = false;
        this.objFading = false;
        this.checkFunc = checkFunc;
        this.obj = obj;
    },

    fadeFin: function()
    {
        this.objFading = false;
    },

    appearFin: function()
    {
        this.objAppearing = false;
    },

    validate: function()
    {
        var ret = this.checkFunc();
        if (!this.showed && ret && !this.objAppearing)
        {
            this.objAppearing = true;
            this.showed = true;
            new Effect.Appear(this.obj,this.appearFin.bind(this));
        }
        else if (this.showed && !ret && !this.objFading)
        {
            this.objFading = true;
            this.showed = false;
            new Effect.Fade(this.obj,this.fadeFin.bind(this));
        }
        return !ret;
    }
};

var USERID_RE = /^[A-Z0-9_\.]{6,16}$/i;
var PASSWORD_RE = /^[A-Z0-9!@#$%^&*()_-]{6,16}$/i;
var EMAIL_RE = /^[A-Z0-9._%-]+@[A-Z0-9._%-]+\.[A-Z]{2,6}$/i;
var DATETIME_RE = /^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01]) (20|21|22|23|[0-1]\d):[0-5]\d$/;
var DATE_RE = /^(19|20)\d\d-(0[1-9]|1[012])-(0[1-9]|[12][0-9]|3[01])$/;
var NUMBER_RE = /^[-]*[0-9]*$/;
var POSITIVENUMBER_RE = /^[+]?[0-9]+$/;
var NEGATIVENUMBER_RE = /^-[0-9]+$/;
var NUMERIC_RE = /^[0-9]+(.[0-9]+)?$/;

function validate_numeric(input)
{
	return NUMERIC_RE.test(input);
}

function validate_positivenumber(input)
{
    return POSITIVENUMBER_RE.test(input);
}

function validate_negativenumber(input)
{
    return NEGATIVENUMBER_RE.test(input);
}

function validate_number(input)
{
    return NUMBER_RE.test(input);
}

function validate_userid(input)
{
    return USERID_RE.test(input);
}

function validate_password(input)
{
    return PASSWORD_RE.test(input);
}

function validate_email(input)
{
    return EMAIL_RE.test(input);
}

function check_date(year,month,day)
{
    if (day==31 && (month==4 || month==6 || month==9 || month==11))
        return false;
    else if (day>=30 && month==2)
        return false;
    else if (month==2 && day==29 && !(year%4==0 && (year%100!=0 || year%400==0)))
        return false;
    else
        return true;
}

function validate_date(input)
{
    if (DATE_RE.test(input))
    {
        var chunks = input.split("-");
        var year = new Number(chunks[0]);
        var month = new Number(chunks[1]);
        var day = new Number(chunks[2]);
        return check_date(year,month,day);
    }
    else
        return false;
}

function validate_datetime(input)
{
    if (DATETIME_RE.test(input))
    {
        var chunks = input.split("-");
        var dayChunks = chunks[2].split(" ");
        var year = new Number(chunks[0]);
        var month = new Number(chunks[1]);
        var day = new Number(dayChunks[0]);
        return check_date(year,month,day);
    }
    else
        return false;
}

function hisObj(container, path, action, param, type)
{
	this.container = container;
	this.path = path;
	this.action = action;
	this.param = param;
	this.type = type;
	this.toString = function()
	{
		return '[Container:'+this.container+' Path:'+this.path+' Action:'+
				this.action+' Param:'+this.param+' Type:'+this.type+']';
	};
}

function historyManager()
{
	this.historyLength = 5;
	this.hisStack = new Array(1);
	this.addHistory = function(hisObj)
	{
	    if (hisObj && hisObj.type!='inner')
	    {
    		if (this.hisStack.length>=this.historyLength)
    			this.hisStack.shift();
    		this.hisStack.push(hisObj);
    	}
	};
	this.getCurrent = function()
	{
		return this.hisStack[this.hisStack.length-1];
	};
	this.getHistory = function()
	{
		if (this.hisStack.length>1)
		{
			return this.hisStack[this.hisStack.length-2];
		}
		else if (this.hisStack.length>0)
		{
			return this.hisStack[this.hisStack.length-1];
		}
		else
		{
			return null;
		}
	};
	this.popCurrent = function()
	{
		return this.hisStack.pop();
	};
}

var _currentManager = new historyManager();
var _historyManager = new historyManager();
var initHistory = new hisObj('src','/getPage.wish','wish','','normal');
_historyManager.addHistory(initHistory);
_currentManager.addHistory(initHistory);

function handleGenericHistory(container,action,param,type)
{
	switch (action)
	{
		case 'wish':
		case 'about':
		case 'how':
		case 'activate':
		case 'privacy':
		case 'termsofuse':
		case 'itemIndex':
		case 'itemDetail':
		case 'itemCatalog':
		case 'forgetPassword':
		case 'register':
		case 'checkOrder':
		case 'getOrderDetail':
		case 'paymentNotice':
		case 'getPaymentDetail':
		case 'showCart':
		case 'showWishlist':
		case 'enquiry':
		case 'modifyAccount':
		case 'getNoticeDetail':
		case 'getSpecialOfferDetail':
		case 'messageBoard':
		case 'getCreateTopicPage':
		case 'getReplyPage':
		case 'menuPage':
		case 'webring':
		case 'getGalleryList':
		case 'getGalleryDetail':
		case 'getManageGalleryList':
		case 'getManageGalleryDetail':
		case 'getManageGalleryImages':
			var tmpHisObj = new hisObj(container,'/getPage.wish',action,param,type);
			_historyManager.addHistory(tmpHisObj);
			_currentManager.addHistory(tmpHisObj);
			break;
	}
}

function generic_output(container,action,param,appear,type,addHistory)
{
    clearACDiv();
    if (!param) param='';
    if (!appear) appear=false;
    if (!type) type = 'get';
    if (!addHistory) addHistory = true;
    if (addHistory)
    {
	    handleGenericHistory(container,action,param,'normal');
	}
    new Ajax.Updater(container,'/getPage.wish',
        {
            method: type,
            parameters: 'action='+action+param,
			evalScripts: true,
            onComplete: function()
            {
            	hideInnerWin();
                if (appear)
                {
                    $(container).style.display = 'none';
                    new Effect.Appear(container,dummy);
                }
            }
        });
}

function admin_output(container,action,param,appear,type,addHistory)
{
    clearACDiv();
    if (!param) param = '';
    if (!appear) appear = false;
    if (!type) type = 'get';
    if (!addHistory) addHistory = true;
	switch (action)
	{
		case 'index':
		case 'getCreateItemBasic':
		case 'getSearchItem':
		case 'getItemList':
		case 'getItemDetailBasic':
		case 'getMonitorLogList':
		case 'getOrderList':
		case 'getOrderDetail':
		case 'getNoticeList':
		case 'getCreateNotice':
		case 'getNoticeDetail':
		case 'getUserList':
		case 'getUserDetail':
		case 'getCreateNewsletter':
		case 'getNewsletterList':
		case 'getNewsletterDetail':
		case 'getItemDetailBasic':
		case 'getItemDetailImg':
		case 'getReportPage':
		case 'getGalleryList':
		case 'getGalleryDetail':
		case 'getAddGalleryPage':
		case 'getOrderHelper':
			var tmpHisObj = new hisObj(container,'/getAdminPage.wish',action,param,'normal');
			if (addHistory)
			{
			    _historyManager.addHistory(tmpHisObj);
			    _currentManager.addHistory(tmpHisObj);
			}
			break;
	}
    new Ajax.Updater(container,'/getAdminPage.wish',
        {
            method: type,
            parameters: 'action='+action+param,
			evalScripts: true,
            onComplete: function()
            {
            	hideInnerWin();
                if (appear)
                {
                    $(container).style.display = 'none';
                    new Effect.Appear(container,dummy);
                }
            }
        });
}

function changeLanguage(languageid)
{
    clearACDiv();
	var currHisObj = _historyManager.getCurrent();
	var newAction = currHisObj.action;
	var newParam = '&changeLanguage=T&languageid='+languageid;
	var currParam = (currHisObj.param==null)?"":currHisObj.param;
	if (currParam.match(/&changeLanguage=.&languageid=./)==null)
	{
		newParam = currParam + newParam;
	}
	else
	{
		newParam = currParam.replace(/&changeLanguage=.&languageid=./,newParam);
	}
	var newHisObj = new hisObj('root',currHisObj.path,newAction,newParam,'normal');
	_historyManager.addHistory(newHisObj);
	_currentManager.addHistory(newHisObj);
    new Ajax.Updater('root',currHisObj.path,
        {
            method: 'get',
            parameters: 'action='+newAction+newParam,
			evalScripts: true
        });
}

function clearACDiv()
{
    var acDiv = $$('div.autocomplete');
    for (var i=0; i<acDiv.length; i++)
        acDiv[i].remove();
}

function history_back()
{
    clearACDiv();
	var tmpHisObj = _historyManager.getHistory();
	_historyManager.popCurrent();
    new Ajax.Updater(tmpHisObj.container,tmpHisObj.path,
        {
            method: 'get',
            parameters: 'action='+tmpHisObj.action+tmpHisObj.param,
			evalScripts: true
        });
}

function fillSelect(objName,val)
{
	var tmpObj = $(objName).options;
	for (var i=0; i<tmpObj.length; i++)
	{
		if (tmpObj[i].value == val)
		{
			$(objName).selectedIndex = i;
			break;
		}
	}
}

function getPageScroll()
{
	var yScroll;
	if (self.pageYOffset) {
		yScroll = self.pageYOffset;
	} else if (document.documentElement && document.documentElement.scrollTop){
		yScroll = document.documentElement.scrollTop;
	} else if (document.body) {
		yScroll = document.body.scrollTop;
	}
	arrayPageScroll = new Array('',yScroll);
	return arrayPageScroll;
}

function getPageSize()
{
	var xScroll, yScroll;
	
	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;
	}
	
	var windowWidth, windowHeight;
	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,windowWidth,windowHeight);
	return arrayPageSize;
}

function showOverlay()
{
	var pageSize = getPageSize();
	$('overlay').style.height = $('overlayDiv').style.height = pageSize[1];
	var allForms = document.getElementsByClassName('formObj');
	for (var i=0; allForms!=null && i<allForms.length; i++)
		Form.disable(allForms[i]);
	var selObj = document.getElementsByTagName('SELECT');
	if (selObj!=null)
	{
    	for (var j=0;j<selObj.length;j++)
        	selObj[j].disabled = true;
    }
	$('overlayDiv').show();
}

function hideOverlay()
{
	$('overlayDiv').hide();
	var allForms = document.getElementsByClassName('formObj');
	for (var i=0; allForms!=null && i<allForms.length; i++)
		Form.enable(allForms[i]);
	var selObj = document.getElementsByTagName('SELECT');
	if (selObj!=null)
	{
    	for (var j=0;j<selObj.length;j++)
        	selObj[j].disabled = false;
    }
}

function initInnerWin(targetDiv)
{
	showOverlay();
	var pageScroll = getPageScroll();
	var targetWidth = ($(targetDiv).style.width).match('[0-9]*');
	var targetHeight = ($(targetDiv).style.height).match('[0-9]*');
	var pageSize = getPageSize();
	var height = (pageSize[3]-targetHeight)/2;
	var width = width = (pageSize[2]-targetWidth)/2;
	$('innerWin').style.height = targetHeight;
	$('innerWin').style.width = targetWidth;
	$('innerWin').style.top = pageScroll[1] + height;
	$('innerWin').style.left = width;
    $('innerWin').show();
}

function showInnerWinCore(targetDiv, action, param, admin)
{
	if (param==null)
		param = '';
	if (action!=null)
	{
		handleGenericHistory(targetDiv,action,param,'inner');
		var scope = '/getPage.wish';
		if (admin) scope = '/getAdminPage.wish';
		new Ajax.Updater('innerWin',scope,
	        {
	            method: 'get',
	            parameters: 'action='+action+param,
				evalScripts: true,
	            onComplete: function()
	            {
	            	initInnerWin(targetDiv);
	            }
	        });
	}
	else
		initInnerWin(targetDiv);
}

function showInnerWin(targetDiv, action, param)
{
	showInnerWinCore(targetDiv,action,param);
}

function showAdminInnerWin(targetDiv, action, param)
{
	showInnerWinCore(targetDiv,action,param,'true');
}

function hideInnerWin()
{
	$('innerWin').hide();
	hideOverlay();
	$('innerWin').innerHTML = '';
}

function setupInput(objId, tips)
{
	var obj = $(objId);
	obj.value = tips;
	obj.onclick = function()
	{
		if (Trim($(objId).value)==tips)
		{
			$(objId).value = '';
		}
	}.bind(this);
	obj.onfocus = function()
	{
		$(objId).className = 'over';
	};
	obj.onblur = function()
	{
		if (Trim($(objId).value)=='')
		{
			$(objId).value = tips;
		}
		$(objId).className = '';
	}.bind(this);
}

function func_cancel()
{
	_historyManager.addHistory(_historyManager.getHistory());
	hideInnerWin();
	return false;
}

function disableAllButton() {
    var inputs = document.getElementsByTagName('button');
    for(var i=0; i<inputs.length; i++)
        inputs[i].disabled = true;
}

function enableAllButton() {
    var inputs = document.getElementsByTagName('button');
    for(var i=0; i<inputs.length; i++)
        inputs[i].disabled = false;
}

function getPNFn(extra, formName)
{
    var fn = '_pnForm';
    if (formName!=null && formName!='') fn = formName;
	var str = $(fn)._PN_fn.value + 
			  "('" + 
			  $(fn)._PN_target.value + 
			  "','" + 
			  $(fn)._PN_action.value + 
			  "','&" + 
			  Form.serialize(fn) +
			  extra +
			  "');";
	eval(str);
	return false;
}

function getAdminFile(ID)
{
    $('innerWin').innerHTML = "<iframe src='/getAdminPage.wish?action=getAdminFile&ID="+ID+"' style='display:none'>&nbsp;</iframe>";
    return false;
}

var EdenAC = Class.create();
EdenAC.prototype =
{
	initialize: function (obj, options)
	{
		this.obj = $(obj)
		this.obj.setAttribute("AutoComplete","off");
		this.previousVal = "";
        
		this.options = options ? options : {};
		if ($(this.options.id)) $(this.options.id).remove();
		this.options.queryDelay = options.queryDelay ? options.queryDelay : 0.5;
        this._delayId = -1;
		
		this.div = document.createElement('div');
		this.div['id'] = this.options.id;
		this.div['className'] = this.options.className;
		var hCornerDiv = document.createElement('div');
		hCornerDiv.className = 'ac_corner';
		var hBarDiv = document.createElement('div');
		hBarDiv.className = 'ac_bar';
		var headerDiv = document.createElement('div');
		headerDiv.className = 'ac_header';
		headerDiv.appendChild(hCornerDiv);
  	    headerDiv.appendChild(hBarDiv);
  	    this.div.appendChild(headerDiv);
  	    var coreDiv = document.createElement('div');
  	    coreDiv['id'] = "_ac" + this.options.id;
  	    this.div.appendChild(coreDiv);
  	    var fCornerDiv = document.createElement('div');
		fCornerDiv.className = 'ac_corner';
		var fBarDiv = document.createElement('div');
		fBarDiv.className = 'ac_bar';
		var footerDiv = document.createElement('div');
		footerDiv.className = 'ac_footer';
		footerDiv.appendChild(fCornerDiv);
  	    footerDiv.appendChild(fBarDiv);
  	    this.div.appendChild(footerDiv);
		
		var pos = this.obj.cumulativeOffset();
		this.div.style.left = pos[0] + "px";
		this.div.style.top = pos[1] + this.obj.offsetHeight + "px";
		this.div.style.width = this.obj.offsetWidth + "px";
		this.div.style.display = 'none';
		this.index = 0;
		
		this.obj.onkeypress = function(ev){ return this.onKeyPress(ev); }.bind(this);
		this.obj.onkeyup = function(ev){ return this.onKeyUp(ev); }.bind(this);
		this.div.onkeypress = function(ev){ return this.onKeyPress(ev); }.bind(this);
		this.div.onkeyup = function(ev){ return this.onKeyUp(ev); }.bind(this);
		$('root').appendChild(this.div);
	},
	relocate: function()
	{
	    var pos = this.obj.cumulativeOffset();
		this.div.style.left = pos[0] + "px";
		this.div.style.top = pos[1] + this.obj.offsetHeight + "px";
		this.div.style.width = this.obj.offsetWidth + "px";
		this.div.style.display = 'none';
	},
	onKeyPress: function (e)
	{
		if (!e) e = window.event;
	  	var key	= e.keyCode;
		switch(key)
		{
			case Event.KEY_RETURN:
				var list = $("ac_ul");
				this.clear();
				this.obj.setStyle({backgroundImage:'url(../images/autocomplete/spinner.gif)'});
				this.obj.disabled = true;
				
				list.childNodes[this.index-1].onclick();
				Event.stop(e);
				break;
			case Event.KEY_TAB:
				this.highlight(key);
				Event.stop(e);
				break;
			case Event.KEY_ESC:
				this.clear();
				break;
		}
		return true;
	},
	onKeyUp: function (e)
	{
		if (!e) e = window.event;
	  	var key = e.keyCode;
	  	if (key == Event.KEY_UP || key == Event.KEY_DOWN)
	  	{
	  		this.highlight(key);
	  		Event.stop(e);
	  	}
	  	else if (key != Event.KEY_ESC)
	  	{
	  		if (Trim(this.obj.value)=='' && this.previousVal.toString()!=Trim(this.obj.value).toString()) this.clear();
	  		else if (this.previousVal.toString()!=Trim(this.obj.value).toString())
	  		{
	  		    var _delayId = setTimeout(function()
                  {
                      this.getContentList(this.obj.value );   
                  }.bind(this), this.options.queryDelay*1000);
                if (this._delayId!=-1) clearTimeout(this._delayId);
                this._delayId = _delayId;
	  		}
	  		this.previousVal = Trim(this.obj.value);
	  	}
	  	else
	  	    this.previousVal = "";
		return true;
	},
	clear: function()
	{
		var clearFunc = function()
		{
		    if ($("_ac"+this.div.id))
		        $("_ac"+this.div.id).update('');
		};
		new Effect.Fade(this.div.id, clearFunc.bind(this));
	},
	getContentList: function(keywords)
	{
		this.obj.setStyle({backgroundImage:'url(../images/autocomplete/spinner.gif)'});
		new Ajax.Updater("_ac"+this.div.id,this.options.url,
        {
            method: 'get',
            parameters: 'action='+this.options.action + '&keywords=' + keywords + this.options.param,
			evalScripts: true,
            onComplete: function()
            {
            	this.obj.setStyle({backgroundImage:'url(../images/autocomplete/leftcap.gif)'});
            	this.index = 0;
				this.highlight(Event.KEY_DOWN);
				this._delayId = -1;
				
				var opacity = $(this.div.id).getOpacity();
        		if ($(this.div.id).style.display!='block' || opacity==0)
        			new Effect.Appear(this.div.id);
            }.bind(this)
        });
	},
	highlight: function (key)
	{
		var list = $("ac_ul");
		if (!list)
			return false;
		var n;
		n = (key == Event.KEY_DOWN || key == Event.KEY_TAB)? this.index + 1 : this.index - 1;
		n = (n > list.childNodes.length)? list.childNodes.length : ((n < 1)? 1 : n);
		this.index = Number(n);
		this.clearHighlight();
		list.childNodes[this.index-1].className = 'ac_highlight';
	},
	clearHighlight: function()
	{
		var list = $('ac_ul');
	  	if(!list) return false;
	  	for (var i=0; i<list.childNodes.length; i++)
	  	{
	  		list.childNodes[i].className='';
	  	}
	}
};

var EdenCS = Class.create();
EdenCS.prototype =
{
	initialize: function (selector, options)
	{
		this.selector = $(selector);
		this.selector.onchange = function() { this.getOptions(); }.bind(this);;
		this.options = options ? options : {};

		this.checkboxName = this.options.checkboxName;
		this.div = $(this.options.divId);
		this.originalDivSrc = this.div.innerHTML;
		this.form = $(this.options.formId);
		
		this.csArr = $H();
	},
	checkExist: function (key, val)
	{
		if (key!=null && key!='' && !this.csArr.get(key))
		{
			this.csArr.set(key,val);
			return false;
		}
		else
			return true;
	},
	clear: function()
	{
	    this.csArr = $H();
	    this.div.update(this.originalDivSrc);
	},
	getOptions: function()
	{
		var selectName = this.selector.options[this.selector.selectedIndex].text;
		var selectVal = this.selector.options[this.selector.selectedIndex].value;
		if (!this.checkExist(selectName, selectVal))
		{
			var cb = document.createElement("input");
			cb.type = "checkbox";
			cb.name = this.checkboxName;
			cb.value = selectVal;
			$(cb).onclick = function () 
							{
								$(newDiv).remove();
								this.csArr.unset(selectName);
							}.bind(this);
			$(cb).onfocus = function () {if(this.blur) this.blur()};
			
			var newDiv = document.createElement('div');
			$(newDiv).insert(cb);
			$(newDiv).insert("&nbsp;");
			$(newDiv).insert(selectName);
			$(newDiv).insert("<br>");
			this.div.insert(newDiv);
			
			cb.checked = true;
		}
	}
};