var VHM = VHM || {};
VHM.Core = VHM.Core || {};

VHM.Core.EventUtil = VHM.Core.EventUtil || {};
VHM.Core.EventUtil.addEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.addEventListener) {
        oTarget.addEventListener(sEventType, fnHandler, false);
    } else if (oTarget.attachEvent) {
        oTarget.attachEvent("on" + sEventType, fnHandler);
    } else {
        oTarget["on" + sEventType] = fnHandler;
    }
};        
VHM.Core.EventUtil.removeEventHandler = function (oTarget, sEventType, fnHandler) {
    if (oTarget.removeEventListener) {
        oTarget.removeEventListener(sEventType, fnHandler, false);
    } else if (oTarget.detachEvent) {
        oTarget.detachEvent("on" + sEventType, fnHandler);
    } else { 
        oTarget["on" + sEventType] = null;
    }
};
VHM.Core.EventUtil.formatEvent = function (oEvent) {
    if (typeof oEvent.charCode == "undefined") {
        oEvent.charCode = (oEvent.type == "keypress") ? oEvent.keyCode : 0;
        oEvent.isChar = (oEvent.charCode > 0);
    }
    
    if (oEvent.srcElement && !oEvent.target) {
        oEvent.eventPhase = 2;
        oEvent.pageX = oEvent.clientX + document.body.scrollLeft;
        oEvent.pageY = oEvent.clientY + document.body.scrollTop;
        
        if (!oEvent.preventDefault) {
                oEvent.preventDefault = function () {
                    this.returnValue = false;
                };
        }

        if (oEvent.type == "mouseout") {
            oEvent.relatedTarget = oEvent.toElement;
        } else if (oEvent.type == "mouseover") {
            oEvent.relatedTarget = oEvent.fromElement;
        }

        if (!oEvent.stopPropagation) {
                oEvent.stopPropagation = function () {
                    this.cancelBubble = true;
                };
        }
        
        oEvent.target = oEvent.srcElement;
        oEvent.time = (new Date).getTime();
    
    }
    
    return oEvent;
};
VHM.Core.EventUtil.getEvent = function() {
    if (window.event) {
        return this.formatEvent(window.event);
    } else {
        return VHM.Core.EventUtil.getEvent.caller.arguments[0];
    }
};

VHM.Core.Image = VHM.Core.Image || {};
VHM.Core.Image.MM_preloadImages = function() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=VHM.Core.Image.MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
};
VHM.Core.Image.MM_swapImgRestore = function() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
};
VHM.Core.Image.MM_findObj = function(n, d) { //v4.01
  var p,i,x;  if(!d) d=document; if((p=n.indexOf("?"))>0&&parent.frames.length) {
    d=parent.frames[n.substring(p+1)].document; n=n.substring(0,p);}
  if(!(x=d[n])&&d.all) x=d.all[n]; for (i=0;!x&&i<d.forms.length;i++) x=d.forms[i][n];
  for(i=0;!x&&d.layers&&i<d.layers.length;i++) x=VHM.Core.Image.MM_findObj(n,d.layers[i].document);
  if(!x && d.getElementById) x=d.getElementById(n); return x;
};
VHM.Core.Image.MM_swapImage = function() { //v3.0
  var i,j=0,x,a=VHM.Core.Image.MM_swapImage.arguments; document.MM_sr=new Array; for(i=0;i<(a.length-2);i+=3)
   if ((x=VHM.Core.Image.MM_findObj(a[i]))!=null){document.MM_sr[j++]=x; if(!x.oSrc) x.oSrc=x.src; x.src=a[i+2];}
};
VHM.Core.Image.MM_showHideLayers = function () { //v6.0
  var i,p,v,obj,args=VHM.Core.Image.MM_showHideLayers.arguments;
  for (i=0; i<(args.length-2); i+=3) if ((obj=VHM.Core.Image.MM_findObj(args[i]))!=null) { v=args[i+2];
    if (obj.style) { obj=obj.style; v=(v=='show')?'visible':(v=='hide')?'hidden':v; }
    obj.visibility=v; }
}

VHM.Core.ScriptUtil = VHM.Core.ScriptUtil || {};
VHM.Core.ScriptUtil.scriptList = null;
VHM.Core.ScriptUtil.initialize = function(){
	var aScript = document.getElementsByTagName("script");
	this.scriptList = new Array();
	for(i in aScript){
		if(aScript[i].src && aScript[i].src != ""){
			this.scriptList.push(aScript[i]);
		}
	}
};
VHM.Core.ScriptUtil.hasScript = function(sPath){
	VHM.Core.ScriptUtil.initialize();
		
	var sSrchTarget = sPath.toLowerCase().replace(/\.\.\//g,"");
	sSrchTarget = ((sSrchTarget.substring(0) != "/")?"/":"") + sSrchTarget;
	var bHasScript = false;
	
	for(p in this.scriptList){
		var oScript = this.scriptList[p];
		if(oScript.src && oScript.src.toLowerCase().indexOf(sSrchTarget) > -1){
			bHasScript = true;
			break;
		}
	}
	return bHasScript;
};
VHM.Core.ScriptUtil.addScript = function(sPath){
	var aHead = document.getElementsByTagName("head");
	if(!this.hasScript(sPath)){
		var oScript = document.createElement("script");
		oScript.language = "javascript";
		oScript.type = "text/javascript";
		oScript.src = sPath;
		
		if(aHead.length == 1){
			var oHead = aHead[0];
			oHead.appendChild(oScript);
		}
		else if(aHead.length == 0){
			throw "No head tag exists.";
		}
		else{
			throw "Multiple head tag found.";
		}
	}
};

VHM.Core.StringBuilder = function(value){
	this.strings = new Array("");
	this.append(value);
};
VHM.Core.StringBuilder.prototype = {
	append : function(value){
		if(value){
			this.strings.push(value);
		}
	},	
	clear : function(){
		this.strings.length = 1;
	},
	toString : function(){
		return this.strings.join("");
	}
};
VHM.Core.ReadCookie = function(name) {
    var nameEQ = name + "=";
    var ca = document.cookie.split(';');
    for (var i = 0; i < ca.length; i++) {
        var c = ca[i];
        while (c.charAt(0) == ' ') c = c.substring(1, c.length);
        if (c.indexOf(nameEQ) == 0)
            return c.substring(nameEQ.length, c.length);
    }
    return null;
}
VHM.Core.Util = VHM.Core.Util || {};
VHM.Core.Util.Position = function (obj){
	this.x = VHM.Core.Util.findPosX(obj);
	this.y = VHM.Core.Util.findPosY(obj);
};
VHM.Core.Util.findPosX = function(obj){
	var curleft = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curleft += obj.offsetLeft
			obj = obj.offsetParent;
		}
	} else if (obj.x)
		curleft += obj.x;
	return curleft;
};
VHM.Core.Util.findPosY = function(obj){
	var curtop = 0;
	if (obj.offsetParent) {
		while (obj.offsetParent) {
			curtop += obj.offsetTop
			obj = obj.offsetParent;
		}
	} else if (obj.y)
		curtop += obj.y;
	return curtop;
};
VHM.Core.Util.getElmsWithBackgroundImage = function(context){
	var res = [];
	context.find('*').filter(function(){
		return ( this.style.backgroundImage !== ''  );
	}).map(function(){
		res.push({elm:this, bgi:this.style.backgroundImage});
	});
	return res;
};
VHM.Core.Util.restoreBackgroundImage = function(elms){
	if(elms.length){
		var l = elms.length;
		var e;
		for(var i=0; i<l; i++){
			e = elms[i];
			if(typeof e.elm !== "undefined" && typeof e.bgi !== "undefined"){
				e.elm.style.backgroundImage = e.bgi;
			}
		}
	}
};
VHM.Core.Util.HtmlDecode = function (str) {
    if (str && str.length) {
        var m = str.match(/&#\d+;/g);
        if (m) {
            for (var i = 0, l = m.length; i < l; i++) {
                var el = m[i].match(/\d+/)[0];
                el = parseInt(el).toString(16);
                str = str.replace(m[i], '%' + el);
            }
            str = unescape(str);
        }
        str = str.replace(/&amp;/gi, "&").replace(/&lt;/gi, "<").replace(/&gt;/gi, ">").replace(/&quot;/gi, "\"");
    }
    return str;
};
VHM.Core.Util.getFlashVersion = function () { //http://www.prodevtips.com/2008/11/20/detecting-flash-player-version-with-javascript/
    try { //IE
        try {
            // avoid fp6 minor version lookup issues
            // see: http://blog.deconcept.com/2006/01/11/getvariable-setvariable-crash-internet-explorer-flash-6/
            var axo = new ActiveXObject('ShockwaveFlash.ShockwaveFlash.6');
            try { axo.AllowScriptAccess = 'always'; }
            catch (e) { return '6,0,0'; }
        } catch (e) { }
        return new ActiveXObject('ShockwaveFlash.ShockwaveFlash').GetVariable('$version').replace(/\D+/g, ',').match(/^,?(.+),?$/)[1];
    } catch (e) { // other browsers
        try {
            if (navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin) {
                return (navigator.plugins["Shockwave Flash 2.0"] || navigator.plugins["Shockwave Flash"]).description.replace(/\D+/g, ",").match(/^,?(.+),?$/)[1];
            }
        } catch (e) { }
    }
    return '0,0,0';
}
VHM.Core.Util._ExecFunc = [];
VHM.Core.Util.ExecFuncWhenCondition = function (f, condition_func, args) {
    if (typeof f !== "function") {
        throw "f must be a function";
    } else {
        if (typeof condition_func !== "function") {
            f(args);
        } else {
            (function () {
                if (!condition_func()) {
                    VHM.Core.Util._ExecFunc[f] = setTimeout(arguments.callee, 10);
                } else {
                    VHM.Core.Util._ExecFunc[f] = null;
                    f(args);
                    f = condition_func = null;
                }
            })();
        }
    }
};
VHM.Core.Util.ExitFuncWhenCondition = function (f) {
    clearTimeout(VHM.Core.Util._ExecFunc[f]);
}
VHM.Core.Util.GetUrlParameters = function () {
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for (var i = 0; i < hashes.length; i++) {
        hash = hashes[i].split('=');
        vars.push(hash[0]);
        vars[hash[0]] = hash[1];
    }
    return vars;
}
VHM.Core.Util.FormatNumber = function (number) {

    var _n = parseInt(number);
    if (number == null || number == undefined || isNaN(number)) return number;

    _n += '';
    x = _n.split('.');
    x1 = x[0];
    x2 = x.length > 1 ? '.' + x[1] : '';
    var rgx = /(\d+)(\d{3})/;
    while (rgx.test(x1)) {
        x1 = x1.replace(rgx, '$1' + ',' + '$2');
    }
    return x1 + x2;
}

VHM.Core.Validation = VHM.Core.Validation || {};

VHM.Core.Validation.CheckEmail = function(emailAdd){
	filter = /^[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+(?:[A-Z]{2}|com|org|net|gov|edu|mil|biz|info|mobi|name|aero|jobs|museum)\b$/i;
	return filter.test(emailAdd);
}

/**
*	WebService Object :	Javascript/WebService interaction
*	Author :	Jimmy Hattori	(jimmy.hattori@ringboxingclub.com)
*	Version :	1.0	(2007/11/6)
**/
VHM.Core.WebService = function(action,url,fn){
	this.functionName=fn;
	this.action=(action)?action+this.functionName:" ";
	this.url=(url)?url:"";
	this.nspace =(action)?action:"";
	
	if (window.XMLHttpRequest)
	{
		this._xmlhttp = new XMLHttpRequest();
	}
	else if (window.ActiveXObject)
	{
		this._xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}
	else
	{
		throw new Error("XMLHttpRequest or ActiveXObject is not supported.");
	}
};
VHM.Core.WebService.prototype = {
	loading : function (){},
	loaded : function (){},
	interactive : function (){},
	complete : function (status,statusText,responseText,responseHTML){},
	soap : function(aParam){
		try
		{
			var instance = this;
			var sParam = this.buildSoapReq(aParam);
			
			if(this._xmlhttp.overrideMimeType){
				this._xmlhttp.overrideMimeType("text/xml");
			}
			this._xmlhttp.open("post", this.url, true);
			this._xmlhttp.setRequestHeader("Content-Type","text/xml");
			this._xmlhttp.setRequestHeader("SOAPAction", this.action);
			this._xmlhttp.setRequestHeader("Content-Length",sParam.length);
			this._xmlhttp.setRequestHeader("Connection","close");
			this._xmlhttp.onreadystatechange = function(){
				switch(instance._xmlhttp.readyState){
					case 1:
						instance.loading();
						break;
					case 2:
						instance.loaded();
						break;
					case 3:
						instance.interactive();
						break;
					case 4:
						instance.complete(instance._xmlhttp.status,
											instance._xmlhttp.statusText,
											instance._xmlhttp.responseText,
											instance._xmlhttp.responseXML);
						break;
				}
			}
			this._xmlhttp.send(sParam);
		}
		catch(e){
			throw new Error("Error has occurred.\nMessage : " + e.message+"\nDescription : " + e.description);
		}
	},
	post : function(aParam){
		try
		{
			var instance = this;
			var sParam = this.buildPostReq(aParam);
			
			if(this._xmlhttp.overrideMimeType){
				this._xmlhttp.overrideMimeType("application/x-www-form-urlencoded");
			}
			this._xmlhttp.open("post", this.url+"/"+this.functionName, true);
			this._xmlhttp.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
			this._xmlhttp.setRequestHeader("Content-Length",sParam.length);
			this._xmlhttp.setRequestHeader("Connection","close");
			this._xmlhttp.onreadystatechange = function(){
				switch(instance._xmlhttp.readyState){
					case 1:
						instance.loading();
						break;
					case 2:
						instance.loaded();
						break;
					case 3:
						instance.interactive();
						break;
					case 4:
						instance.complete(instance._xmlhttp.status,
										instance._xmlhttp.statusText,
										instance._xmlhttp.responseText,
										instance._xmlhttp.responseXML);
						break;
				}
			}
			this._xmlhttp.send(sParam);
		}
		catch(e){
			throw new Error("Error has occurred.\nMessage : " + e.message+"\nDescription : " + e.description);
		}
	},
	buildSoapReq :  function(aParam){
		var oBuffer = new VHM.Core.StringBuilder();
		oBuffer.append("<soap:Envelope ");
		oBuffer.append("xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" ");
		oBuffer.append("xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\" ");
		oBuffer.append("xmlns:soap=\"http://schemas.xmlsoap.org/soap/envelope/\">");
		oBuffer.append("<soap:Body>");
		oBuffer.append("<"+this.functionName+" xmlns=\""+this.nspace+"\">");
		for(key in aParam){
			if(key != "length" && typeof(aParam[key].prototype) == "undefined")
				oBuffer.append("<"+key+">"+aParam[key]+"</"+key+">");
		}
		oBuffer.append("</"+this.functionName+">");
		oBuffer.append("</soap:Body>");
		oBuffer.append("</soap:Envelope>");
		return oBuffer.toString();
	},
	buildPostReq : function(aParam){
		var aPostReqParam = new Array();
		for(p in aParam)
			aPostReqParam.push(p+"="+encodeURI(aParam[p]));
		return aPostReqParam.join("&");
	}
};

VHM.XML = VHM.XML || {};
VHM.XML.loadXMLDoc = function (path) {
    if (window.XMLHttpRequest) {
        xhttp = new XMLHttpRequest();
    }
    else {
        xhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xhttp.open("GET", path, false);
    xhttp.send("");
    return xhttp.responseXML;
}
VHM.XML.parseTextToXMLDOM = function (text) {
    var xmlDom;
    if (window.DOMParser) {
        parser = new DOMParser();
        xmlDom = parser.parseFromString(text, "text/xml");
    } else { // IE
        xmlDom = new ActiveXObject("Microsoft.XMLDOM");
        xmlDom.async = "false";
        xmlDom.loadXML(text);
    }
    return xmlDom;
}
VHM.XML.xsltTransform = function (xmlDoc, xsltPath) {
    var res;
    var xsltDoc = VHM.XML.loadXMLDoc(xsltPath);
    if (window.ActiveXObject) { // IE
        var xslt = new ActiveXObject("Msxml2.XSLTemplate");
        var tmp_xmlDoc = new ActiveXObject("Msxml2.DOMDocument");
        var xslDoc = new ActiveXObject("Msxml2.FreeThreadedDOMDocument");
        var xmlTxt;
        if (typeof xmlDoc.xml !== "undefined"){ 
            xmlTxt = xmlDoc.xml;
        }
        else if (typeof XMLSerializer !== "undefined") { // IE9
            var oXMLSerializer = new XMLSerializer();
            xmlTxt = oXMLSerializer.serializeToString(xmlDoc);
        }
        tmp_xmlDoc.loadXML(xmlTxt);
        xslDoc.loadXML(xsltDoc.xml);
        xslt.stylesheet = xslDoc;
        var xslProc = xslt.createProcessor();
        xslProc.input = tmp_xmlDoc;
        xslProc.transform();
        res = xslProc.output;
    }
    else if (document.implementation && document.implementation.createDocument) { // code for Mozilla, Firefox, Opera, etc.
        var xsltProcessor = new XSLTProcessor();
        xsltProcessor.importStylesheet(xsltDoc);
        res = xsltProcessor.transformToFragment(xmlDoc, document);
    }
    return res;
}
