 
// JavaScript Document

function goApi(){
    $("btn_api").fireEvent("mouseenter").fireEvent("click");
}

function goCom(){
    //window.location.href = "Competition/" + language;
    window.location.href = "Competition/com_result.html";
}

function goCom2(){
    if (language == "de-de") language = "en-us";
  //  window.location.href = "Video/" + language;
}

var hMsg;
var gBlocking = false; // Global Variable to block the input

var hMenu = {
	
	menu : "main",
	initButton : function(){
		this.initAction();
		this.initAnimation();
	},
	
	initAction : function(){
		if (this.menu == "main"){
			if ($defined($("btn_home"))){
				$("btn_home").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section != "home") servePage("home");
					section = "home";
				});
			}
			
			if ($defined($("btn_product"))){
				$("btn_product").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="product") servePage("product");
					section = "product";
					if ($defined($("statframe"))){ $("statframe").src = "stats/product.html" }
				});
			}
			
			if ($defined($("btn_contact"))){
				$("btn_contact").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="contact") servePage("contact");
					section = "contact";
					if ($defined($("statframe"))){ $("statframe").src = "stats/contact.html" }
				});
			}
			
			if ($defined($("btn_get"))){
				$("btn_get").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="iwantthis") servePage("iwantthis");
					section = "iwantthis";
					if ($defined($("statframe"))){ $("statframe").src = "stats/ecard.html" }
				});
			}
			
			if ($defined($("btn_buy"))){
				$("btn_buy").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="buy") servePage("buy");
					section = "buy";
					if ($defined($("statframe"))){ $("statframe").src = "stats/wheretobuy.html" }
				});
			}

            if ($defined($("btn_api"))){
				$("btn_api").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="api") servePage("api");
					section = "api";
					if ($defined($("statframe"))){ $("statframe").src = "stats/wheretobuy.html" }
				});
			}
			
			if ($defined($("btn_com"))){
				$("btn_com").addEvent("click", function(){
					if (!hUser.login) hMsg.getData("loginrequired");
					else {
						hMenu.switchMenu("community");
					}
				});
			}
			
			if ($defined($("bk_com"))){
				if (hUser.login) {
					$("bk_com").addEvent("mouseenter", function(el){
						$("bk_com").setStyle("text-decoration", "underline").setStyle("color", "black");
					});
					$("bk_com").addEvent("mouseleave", function(el){
						$("bk_com").setStyle("text-decoration", "none").setStyle("color", "#999999");
					});
					$("bk_com").addEvent("click", function(el){
						hMenu.switchMenu("community");
						getSubPane("getloginbox");
						//getMainPane("getprofile", "ProfileControl.php", "post");
					});
					$("bk_com").setStyle("display", "");
				}
			}
		} else if (this.menu == "community"){

            // if (console) console.log(hUser.jsUser.product_type);
            
            if (hUser.jsUser.product_type == "1"){
                $("btn_search").setStyle("display", "block");
                $("btn_sequence").setStyle("display", "block");
                $("btn_download").setStyle("display", "block");
                $("btn_message").setStyle("display", "block");
            } else if (hUser.jsUser.product_type == "2"){
                $("btn_mobile").setStyle("display", "block");
                $("btn_search").setStyle("display", "block");
            }

//            $("btn_search").setStyle("display", "block");
//            $("btn_sequence").setStyle("display", "block");
//            $("btn_download").setStyle("display", "block");
//            $("btn_message").setStyle("display", "block");

			// community menu
			if ($defined($("btn_profile"))){
				//console.log("profile clicked");
				$("btn_profile").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section != "community") getMainPane("getprofile", "ProfileControl.php", "post");
					section = "community";
				});
			}

            if ($defined($("btn_mobile"))){
				//console.log("profile clicked");
				$("btn_mobile").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section != "mobile") getMainPane("getmobiletemplate");
					section = "mobile";
				});
			}
			
			if ($defined($("btn_search"))){
				$("btn_search").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="search") getMainPane("getsearchtemplate", "SearchControl.php", "post", function(){
						if (hSearch.search.cache){
							$("search_div").setStyle("display", "block");
							$("search_result").setHTML(hSearch.search.cache);
						}
						hSearch.menu.init();
					});
					section = "search";
				});
			}
			
			if ($defined($("btn_message"))){
				$("btn_message").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="message") getMainPane("getmessagetemplate", "MessageControl.php", "post", function(){
						// fill template here
						hMessage.utility.unboldOldMessage();
						hMessage.utility.initHover();
						hTips.init();
					});
					section = "message";
				});
			}
			
			if ($defined($("btn_sequence"))){
				$("btn_sequence").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					// do here
					if (section != "sequence") getMainPane("getsequencetemplate", "SequenceControl.php", "post", function(data){
						// console.log(data);
					});
					section = "sequence";
					if ($defined($("statframe"))){ $("statframe").src = "stats/motion.html" }
				});
			}
			
			if ($defined($("btn_download"))){
				$("btn_download").addEvent("click", function(){
					$("ajax_content").effects("opacity", 0);
					if (section !="download") getMainPane("getdownloadtemplate");
					section = "download";
				});
			} 
			
			if ($defined($("btn_home2"))){
				$("btn_home2").addEvent("click", function(){
					hMenu.switchMenu("main");
				});
			}
			
			if ($defined($("bk_home"))){
				$("bk_home").addEvent("mouseenter", function(el){
					$("bk_home").setStyle("text-decoration", "underline").setStyle("color", "black");;
				});
				$("bk_home").addEvent("mouseleave", function(el){
					$("bk_home").setStyle("text-decoration", "none").setStyle("color", "#999999");;
				});
				$("bk_home").addEvent("click", function(el){
					hMenu.switchMenu("main", false);
				});
			}
		}
	},
	initAnimation : function(){
		setDrag();

		var menuitems = $$("span[class=menu_item]");
	
		menuitems.each(function(el){
								
			el.setProperty("active", "false");
			
			var fx = new Fx.Styles(el.getChildren()[1], {
				duration: 200,
				wait: false
			});
			
			var fxOuter = new Fx.Styles(el, {
				duration: 200,
				wait: false
			});
			
			el.addEvent("mouseenter", function(){
				el.getChildren()[0].setStyle("visibility", "visible");
				el.getChildren()[1].setStyle("background-image", "url(res/common/images/menu_button_bg.jpg)");
				el.getChildren()[2].setStyle("visibility", "visible");
				fx.start({
					"padding-left": 10,
					"padding-right": 10,
					"color": "#FFFFFF"
				});
				fxOuter.start({
					"margin-left": 5,
					"margin-right": 5
				});
			});
			
			el.addEvent("mouseleave", function(){
				if (el.getProperty("active") == "true") return true;
				el.getChildren()[0].setStyle("visibility", "hidden");
				el.getChildren()[1].setStyle("background-image", "none");
				el.getChildren()[2].setStyle("visibility", "hidden");
				fx.stop().set({
					"padding-left": 0,
					"padding-right": 0,
					"color": "#333333"
				});
				fxOuter.stop().set({
					"margin-left": 15,
					"margin-right": 15
				});
			});
			
			el.addEvent("click", function(){
				if (el.getProperty("active") == "true") return false;
				if (el == $("btn_community") && !hUser.login) return false;
				menuitems.each(function(mi){
					if ( mi == el){
						mi.setProperty("active", "true");
					} else {
						mi.setProperty("active", "false");
						mi.fireEvent("mouseleave");
					}
				});
			});
		});		
	},
	switchMenu : function(which, tween){
		if (tween == null) tween = true;
		var param = "";
		if (which == "main"){
			param = "getmenu";
			this.menu = "main";
			$("ajax_content").effects("opacity", 0);
			if (section != "home") servePage("home");
			if ($defined($("btn_home"))) $("btn_home").fireEvent("mouseenter").fireEvent("click");
		}
		if (which == "community"){
			param = "getcommunitymenu";
			this.menu = "community";
		}
		var menuAjax = new Ajax("src/controller/LayoutControl.php", {
			data : {
				action : param,
				ts : new Date().getTime()
			},
			method : "get",
			update : $("main_menu"),
			onComplete : function(data){
				hMenu.initButton();
				if (tween){
					hMenu.tweenDefault();
				} else {
					$("btn_home").fireEvent("mouseenter");
					section = "home";
				}
				//$("ajax_content").effects("opacity", 0);
				//if (section != "home") servePage("home");
				//if ($defined($("btn_home"))) $("btn_home").fireEvent("mouseenter").fireEvent("click");
			}
		}).request();
	},
	tweenDefault : function(){
		var btn;
		if (this.menu == "main") btn = $("btn_home");
		if (this.menu == "community") btn = $("btn_profile");
		if (btn) btn.fireEvent("mouseenter");
		if (btn) btn.fireEvent("click");
	}
}

var hUser = {
	login : false,
	jsUser : null,
	initPanel : function(){
		if ($defined("logout")){
			$("logout").addEvent("click", function(){
				hUser.confirmLogout();
			});
		}
	},
	getSessionUser : function(){
		var getUser = new Ajax("LoginControl.php", {
			method: 'post',
			data : {
				action : 'getsessionuser',
				ts : new Date().getTime()
			},
			onComplete : function(data){
				var user = Json.evaluate(data, true);
				if (user && user.login){
					hUser.login = true;
					hUser.jsUser = user;
					section = "community";
					hMenu.switchMenu("community");
					//console.log(hUser.jsUser);
				}
			}
		}).request();
	},
	syncSessionUser : function(fn){
		var getUser = new Ajax("LoginControl.php", {
			method: 'post',
			data : {
				action : 'getsessionuser',
				ts : new Date().getTime()
			},
			onComplete : function(data){
				var user = Json.evaluate(data, true);
				if (user.login){
					hUser.jsUser = user;
					if (fn) hProfile.sync(fn);
					else hProfile.sync();
				}
			}
		}).request();
	},
	confirmLogout : function(){
		hMsg.getData("confirmlogout");
	},
	logout : function(){
		if (gBlocking) return false;
		logoutUser = new Ajax("LoginControl.php", {
			data : {
				action : 'logoutuser',
				ts : new Date().getTime()
			},
			onComplete : function(data){
				hProgressBar.clear();
				hUser.login = false;
				hUser.jsUser = null;
				hMenu.switchMenu("main");
				hMsg.hide();
				getSubPane("getloginbox");
				//getMainPane("gethome");
				//console.log("User Logged Out");
			}
		}).request();
	}
}

var hLogin = {

	getCacheUser : function(){
	},
	initLoginForm : function(){
		var inputFields = $$("#login_form input[type=text]").merge($$("#login_form input[type=password]"));
 
		inputFields.each(function(el){
			el.addEvent("focus", function(){
				el.select();
			});
			el.addEvent("keyup", function(e){
				var evt = new Event(e);
				if (evt.key == "enter"){
                    url = "http://www.i-buddy.com/index.php?lang=";
                    if (typeof language != "undefined"){
                        url = url + language;
                    } else {
                        vlang = window.location.href.match(/lang=.{5}/);
                        if (vlang) url = url + vlang;
                        else {
                            url = url + "en-us";
                        }
                    }
				 
                //   window.location.href = url;
				    
					window.open(url, 'community', 'location=no,titlebar=no,resizable=yes,height=480,width=900', false);
                    return;
                } //hLogin.login();
			});
		});
		$("login_button").addEvent("click", function(){
            url = "index.php?lang=";
            if (typeof language != "undefined"){
                url = url + language;
            } else {
                vlang = window.location.href.match(/lang=.{5}/);
                if (vlang) url = url + vlang;
                else {
                    url = url + "en-us";
                }
            }
	
             //window.location.href = url;
		//	window.open(url, 'community');
          //  return;
//			gBlocking = true;
//			$("blocker").setStyle("display", "block").setStyle("width", window.getScrollWidth()).setStyle("height", window.getScrollHeight()).setOpacity(0.01);
//			this.blur();
			hLogin.login();
		});
	},
	showProgress : function(){
		hProgressBar.init();
		$("login_button_div").setStyle("display", "none");
		$("login_progress_div").setStyle("display", "block");
	},
	showButton : function(){
		hProgressBar.clear();
		$("login_button_div").setStyle("display", "block");
		$("login_progress_div").setStyle("display", "none");
	},
	login : function(){
       
        // lang = window.location.href.match(/lang=.{5}/);
		hProgressBar.clear();
		var loginAjax = new Ajax("LoginControl.php", {
			data : $("login_form"),
			onRequest: function(){
				hProgressBar.clear();
			},
			onComplete: function(data){
	
				gBlocking = false;
				$("blocker").setStyle("display", "none");
				var user = Json.evaluate(data, true);
				if (user.login){
					flag = $("remember_me").getValue();
					if (flag){
						hLoginCookie.rememberLogin($("input_login").getValue(), $("input_password").getValue());
					} else {
						hLoginCookie.forgetLogin();
					}
					hUser.jsUser = user;
					hUser.login = true;
					hMenu.switchMenu("community");
					hLogin.showButton();
					hLogin.getPanel();
					//getMainPane("getprofile", "ProfileControl.php", "post");
				}
				else hLogin.printLoginError();
			}
		});
		hLogin.showProgress();
		(function(){loginAjax.request()}).delay(1000);
	},
	printLoginError : function(){
		hMsg.getData("loginfailed");
		hLogin.showButton();
		console.log("LOGIN INCORRECT!");
	},
	forgetPassword : function(){
 
		hMsg.getData("forgetpassword");
	},
	resetPassword : function(){
		if ( ($("forgetpassword_entry").getValue().trim().length == 0 ) ){
			$("forgetpassword_entry").setStyle("border-color", "red");
		} else {
			var passwordAjax = new Ajax("LoginControl.php", {
				method : "post",
				data: {
					"action" : "resetpassword",
					"email" : $("forgetpassword_entry").getValue().trim()
				},
				onRequest: function(){
				},
				onComplete: function(data){
					if (data == "0"){
						// not found
						hMsg.getData("forgetpassword_failed");
					} else if (data == "1"){
						// mail sent
						hMsg.getData("forgetpassword_succeed");
					} else {
						// unknown error
					}
					/*var reply = Json.evaluate(data, true);
					hTips.init();*/
					gBlocking = false;
				}
			}).request();
		}
	},
	getPanel : function(){
		getSubPane("getuserpanel");
	}
}

var hProgressBar = {
	init : function(){
		var bars = $$("div[class=progress_bar]");

		bars.each(function(bar){
			if (bar.getProperty("anim") == "true"){
				bar.fireEvent("start");
				return 0;
			}
			bar.setProperty("anim", "true");
			var play;
			var anim = function(){
				bar.setStyle("background-position", bar.getStyle("background-position").toInt()+5);
			}
			//play = anim.periodical(20);
			bar.addEvent("start", function(){
				play = anim.periodical(20);
			});
			
			bar.addEvent("stop", function(){
				$clear(play);
			});
			
			bar.fireEvent("start");
		});
	},
	clear : function(){
		var bars = $$("div[class=progress_bar]");

		bars.each(function(bar){
			bar.fireEvent("stop");
		});
	}
}

var hReg = {
	jsCheckName : function(){
	},
	jsCheckEmail : function(){
	},
	jsCheckSN : function(){
	},
	createSerial : function(){
		$("serial_generator").value = $("sn0").getValue() + "-" + $("sn1").getValue() + "-" + $("sn2").getValue() + "-" + $("sn3").getValue();
	},
	initAccord : function(){
		$$("div[class=main_accord]").each(function(div){

			var target = div.getNext();
			var slide = new Fx.Slide(target);
			
			div.setStyle("cursor", "pointer");				
			div.addEvent("click", function(){
				slide.toggle();
				//console.log(target);
			});											  
		});
	},
	initRegForm : function(){
		
		$$("#reg_form input[class!=anim_btn]").addEvent("focus", function(){ this.select() });
		
		this.autoFill();
		
		var snFields = [$("sn0"), $("sn1"), $("sn2"), $("sn3")];
		
		snFields.each(function(snf, idx){
			snf.addEvent("keyup", function(evt){
				var e = new Event(evt);
				if ( ( e.code>=48 && e.code<=57 ) || ( e.code>=65 && e.code<=90 ) ){
					if (this.getValue().length == "4"){
						this.value = this.getValue().toUpperCase();
						if ($defined(snFields[idx+1])) snFields[idx+1].focus();
						else $("first_name").focus();
					}
				}
			});
			snf.addEvent("blur", hReg.createSerial);
		});
		
		$("submit_form").addEvent("click", function(){
			$("submit_form").blur();
			hReg.showLoader();
			hReg.clearError();
			$("blocker").setStyle("display", "block").setStyle("width", window.getScrollWidth()).setStyle("height", window.getScrollHeight()).setOpacity(0.01);
			(function(){hReg.submitRegForm()}).delay(1000);
		});
		$("reset_reg_form").addEvent("click", function(){
			hReg.clearError();
		});
		
		hInput.initInputField();
	},
	
	autoFill : function(){
		if (registerParam.sn.length == 16){
			$("sn0").setProperty("value", registerParam.sn.substring(0, 4).toUpperCase());
			$("sn1").setProperty("value", registerParam.sn.substring(4, 8).toUpperCase());
			$("sn2").setProperty("value", registerParam.sn.substring(8, 12).toUpperCase());
			$("sn3").setProperty("value", registerParam.sn.substring(12, 16).toUpperCase());
			hReg.createSerial();
		}
		
		d = new Date();
		offset = (parseInt(d.getTimezoneOffset()/6 * -1))/10;
		$$("option[tag=gmt_item]").each(function(el){
			if (el.value == offset) el.setProperty("selected", "selected");
		});
	},
	
	showLoader : function(){
		hProgressBar.init();
		$("reg_form_loader").setStyle("display", "block");
		$("reg_form_button").setStyle("display", "none");
	},
	showButton : function(){
		hProgressBar.clear();
		$("reg_form_loader").setStyle("display", "none");
		$("reg_form_button").setStyle("display", "block");
	},
	hideControl : function(){
		$("reg_form_loader").setStyle("display", "none");
		$("reg_form_button").setStyle("display", "none");
	},
	
	showSucceed : function(){
		hProgressBar.clear();
		var oldFx = new Fx.Slide("reg_form", {
			duration: 1000,
			onComplete: function(){ 
				$("reg_succeed").setStyle("display", "block");
				var newFx = new Fx.Slide("reg_succeed", {
					duration: 1000
				}).hide().slideIn();
			}
		}).slideOut();
	},
	
	clearError : function(){
		var fields = [
			$$("span[tag=product_model]")[0], $$("span[tag=product_sn]")[0], $$("span[tag=firstname]")[0], $$("span[tag=lastname]")[0],$$("span[tag=nickname]")[0],
			$$("span[tag=email]")[0], $$("span[tag=password]")[0], $$("span[tag=pwd_confirm]")[0], $$("span[tag=vercode]")[0],
			$("reg_product_error"), $("reg_personal_error"), $("reg_ver_error")
		];
		fields.each(function(el){
			el.setHTML();
		});
	},
	
	submitRegForm : function(){
		var hAjaxSubmitForm = new Ajax("regControl.php", {
			data : $("reg_form"),
			onRequest: function(){
				
			},
			onComplete : function(data){
				var result = Json.evaluate(data, true);
				$("blocker").setStyle("display", "none")
				//console.log(result);
				if (result.count>0){
					
					// Show alert
					hMsg.getData("regerror");
					
					// Show the buttons
					hReg.showButton();
					
					// Product
					var product_error = 0;
					if (result.product_model){
						$$("span[tag=product_model]")[0].setHTML(result.product_model);
						product_error++;
					}
					if (result.product_sn){
						$$("span[tag=product_sn]")[0].setHTML(result.product_sn);
						product_error++;
					}
					if (product_error == 0) $("reg_product_error").empty();
					else $("reg_product_error").setHTML("... " + product_error + " Error(s)");

					// Personal Information
					var personal_error = 0;
					if (result.firstname){
						$$("span[tag=firstname]")[0].setHTML(result.firstname);
						personal_error++;
					}
					if (result.lastname){
						$$("span[tag=lastname]")[0].setHTML(result.lastname);
						personal_error++;
					}
					if (result.email){
						$$("span[tag=email]")[0].setHTML(result.email);
						personal_error++;
					}
					if (result.password){
						$$("span[tag=password]")[0].setHTML(result.password);
						personal_error++;
					}
					if (result.pwd_confirm){
						$$("span[tag=pwd_confirm]")[0].setHTML(result.pwd_confirm);
						personal_error++;
					}
					if (result.nickname){
						$$("span[tag=nickname]")[0].setHTML(result.nickname);
						personal_error++;
					}
					if (personal_error == 0) $("reg_personal_error").empty();
					else $("reg_personal_error").setHTML("... " + personal_error + " Error(s)");
					
					// Verification Code Error
					var ver_error = 0;
					if (result.vercode){
						$$("span[tag=vercode]")[0].setHTML(result.vercode);
						ver_error++;
					}
					if (ver_error == 0) $("reg_ver_error").empty();
					else $("reg_ver_error").setHTML("... " + ver_error + " Error(s)");
				} else {
					// registration succeed
					hReg.showSucceed();
				}
			}
		}).request();
	}
}

var hInput = {
	initButton : function(){
		var buttons = $$("input[class=anim_btn]");
		buttons.each(function(el){
			//el.removeEvents();
			if (el.getProperty("tween") == "true") return false;
			var yOffset = 0;
			var play;
			var anim = function(){
				offset = "0px " + yOffset + "px";
				el.setStyle("background-position", offset);
				yOffset -= 1;
			}
			el.addEvent("mouseenter", function(){
				play = anim.periodical(20);
			});
			el.addEvent("mouseleave", function(){
				$clear(play);
				el.setStyle("background-position", "0px 40px");
			});
			
			el.setProperty("tween", "true");
		});
	},
	initInputField : function(){
		var inputFields = $$("input[type=text]").merge($$("input[type=password]")).merge($$("select")).remove($$("input[class=anim_btn]"));
		inputFields.each(function(el){
			if (el.getProperty("tween") == "true") return false;
			var fx = new Fx.Style(el, "border-color", {
				duration: 500,
				wait: true
			});
			el.addEvent("focus", function(){
				fx.set("#CC9900");
			});
			el.addEvent("blur", function(){
				fx.set("#999999");
			});
			el.setProperty("tween", "true");
		});
	}
}

var hProfile = {
	currentAccord : 0,
	utility: {
		displayFileUploadError : function(){
			//hMsg.hide();
			$("close_msg_box").focus();
			(function(){hMsg.getData("displayuploaderror")}).delay(0);
		},
		updatePhoto : function(){
			$("close_msg_box").focus();
			$("close_msg_box").fireEvent("click");
			/*$("user_photo").src = $("user_photo").src+"?ts="+new Date().getTime();
			$("user_photo2").src = $("user_photo2").src+"?ts="+new Date().getTime();*/
			var pic = "usr/user_photo/" + hUser.jsUser.user_id + "/main/main.jpg.profile.jpg";
			$("user_photo").src = pic + "?ts="+new Date().getTime();
			$("user_photo2").src = pic + "?ts="+new Date().getTime();
		},
		updateBuddyPhoto : function(){
			$("close_msg_box").focus();
			$("close_msg_box").fireEvent("click");
			//$("user_photo3").src = $("user_photo3").src+"?ts="+new Date().getTime();
			var pic = "usr/user_photo/" + hUser.jsUser.user_id + "/main/buddy.jpg.tn.jpg";
			$("user_photo3").src = pic + "?ts="+new Date().getTime();
		},
		checkDOB : function(){
			$("date").value = $("date").getValue().trim();
			//console.log($("date").value);
			var d = $("date").getValue();
			if (d.length>0)
				if (!d.test("^[0-9]{4}-[0-9]{2}-[0-9]{2}$")){
					$$("span[tag=dob]")[0].setHTML("Invalid format, YYYY-MM-DD required");
				} else $$("span[tag=dob]")[0].setHTML();
			else $$("span[tag=dob]")[0].setHTML();
		}
	},
	showProgress : function(){
		if ($defined($("update_button"))){
			$("update_button").setStyle("display", "none");
			if ($defined($("update_progress"))){
				$("update_progress").setStyle("display", "block");
				hProgressBar.init();
			}
		}
	},
	hideProgress : function(){
		if ($defined($("update_button"))){
			$("update_button").setStyle("display", "block");
			if ($defined($("update_progress"))){
				$("update_progress").setStyle("display", "none");
				hProgressBar.clear();
			}
		}
	},
	initCalendar : function(){
		return false; // disabled
		var myCal = new Calendar({ date: 'Y-m-d' }, {
			navigation: 2,
			direction: -0.5
		});
	},
	initAccord : function(){
		//var aHeads = $$("span[class=toggle]");
		var aHeads = $$("div[class=main_accord]");
		var aContents = $$("div[class=accord_content]");
		var accord = new Accordion(aHeads, aContents, {
			opacity: false,
			display: hProfile.currentAccord
		}, $('accordion'));
	},
	edit : function(el){
		var p;
		if (!window.ie) p = el.getProperty("param");
		if (window.ie) p = el.param;
		switch(p){
			case("general"):
				hMsg.getData("editprofilegeneral");
				break;
			case("intro"):
				hMsg.getData("editprofileintro");
				break;
			case("preferences"):
				hMsg.getData("editprofilepreferences");
				break;
			case("password"):
				hMsg.getData("editprofilepassword");
				break;
			case("profile_photo"):
				hMsg.getData("editprofilephoto");
				break;
			case("ibuddy_photo"):
				hMsg.getData("editibuddyphoto");
				break;
			default:break;
		}
	},
	update : function(el){
		var p;
		var param;
		if (!window.ie) p = el.getProperty("tag");
		if (window.ie) p = el.tag;
		switch(p){
			case("general"):
				$("date").setProperty("value", $("date").getValue().trim());
				param = $("profile_general_form").toQueryString()+ "&ts=" + new Date().getTime();
				hProfile.currentAccord = 0;
				break;
			case("intro"):
				var pIntro = $("ta_intro").getValue();
				pIntro = pIntro.replace(/%/g, "%%");
				pIntro = pIntro.replace(/\n/g, "%L");
				$("xSelf_intro").setProperty("value", pIntro);
				param = $("profile_intro_form").toQueryString()+ "&ts=" + new Date().getTime();
				hProfile.currentAccord = 1;
				break;
			case("preferences"):
				param = $("profile_preferences_form").toQueryString()+ "&ts=" + new Date().getTime();
				hProfile.currentAccord = 2;
				break;
			case("password"):
				param = $("profile_password_form").toQueryString()+ "&ts=" + new Date().getTime();
				hProfile.currentAccord = -1;
				break;
			default:break;
		}
		var update = new Ajax("ProfileControl.php", {
			method: 'post',
			data: param,
			onRequest: function(){
				if ($defined($$("span.table_help[tag=first_name]")[0])) $$("span.table_help[tag=first_name]")[0].setHTML();
				if ($defined($$("span.table_help[tag=last_name]")[0])) $$("span.table_help[tag=last_name]")[0].setHTML();
				if ($defined($$("span.table_help[tag=nick_name]")[0])) $$("span.table_help[tag=nick_name]")[0].setHTML();
				if ($defined($$("span.table_help[tag=gender]")[0])) $$("span.table_help[tag=gender]")[0].setHTML();
				if ($defined($$("span.table_help[tag=dob]")[0])) $$("span.table_help[tag=dob]")[0].setHTML();
				if ($defined($$("span.table_help[tag=location]")[0])) $$("span.table_help[tag=location]")[0].setHTML();
				if ($defined($$("span.table_help[tag=old_password]")[0])) $$("span.table_help[tag=old_password]")[0].setHTML();
				if ($defined($$("span.table_help[tag=new_password]")[0])) $$("span.table_help[tag=new_password]")[0].setHTML();
				if ($defined($$("span.table_help[tag=password_confirm]")[0])) $$("span.table_help[tag=password_confirm]")[0].setHTML();
				if ($defined($$("span.table_help[tag=msn_contact]")[0])) $$("span.table_help[tag=msn_contact]")[0].setHTML();
				//if (reply.intro) $$("span.table_help[tag=location]")[0].setHTML(reply.location);
			},
			onComplete: function(data){
				hProfile.hideProgress();
				var reply = Json.evaluate(data, true);
				if (reply.status == "ok"){
					//var fn = function(){ hProfile.initAccord() }).delay(500);
					hUser.syncSessionUser(function(){
						if (hProfile.currentAccord >= 0) hProfile.initAccord();
					});
					hMsg.hide();
					
				} else {
					if (reply.firstName) $$("span.table_help[tag=first_name]")[0].setHTML(reply.firstName);
					if (reply.lastName) $$("span.table_help[tag=last_name]")[0].setHTML(reply.lastName);
					if (reply.nickName) $$("span.table_help[tag=nick_name]")[0].setHTML(reply.nickName);
					if (reply.gender) $$("span.table_help[tag=gender]")[0].setHTML(reply.gender);
					if (reply.dob) $$("span.table_help[tag=dob]")[0].setHTML(reply.dob);
					if (reply.location) $$("span.table_help[tag=location]")[0].setHTML(reply.location);
					if (reply.oldPassword) $$("span.table_help[tag=old_password]")[0].setHTML(reply.oldPassword);
					if (reply.newPassword) $$("span.table_help[tag=new_password]")[0].setHTML(reply.newPassword);
					if (reply.newPasswordConfirm) $$("span.table_help[tag=password_confirm]")[0].setHTML(reply.newPasswordConfirm);
					if (reply.msnContact) $$("span.table_help[tag=msn_contact]")[0].setHTML(reply.msnContact);
					//if (reply.intro) $$("span.table_help[tag=location]")[0].setHTML(reply.location);
				}
			}
		});//.request();
		hProfile.showProgress();
		(function(){update.request()}).delay(1000);
	},
	sync : function(fn){
		if ($defined($("userpanel_name"))) $("userpanel_name").setHTML(hUser.jsUser.nick_name);
		if ($defined($("profile_first_name"))) $("profile_first_name").setHTML(hUser.jsUser.first_name);
		if ($defined($("profile_last_name"))) $("profile_last_name").setHTML(hUser.jsUser.last_name);
		if ($defined($("profile_nick_name"))) $("profile_nick_name").setHTML(hUser.jsUser.nick_name);
		if ($defined($("profile_timezone"))) $("profile_timezone").setHTML(hUser.jsUser.timezone);
		if ($defined($("profile_gender"))){
			if (hUser.jsUser.gender == "U") $("profile_gender").setHTML("--- Unspecified ---");
			if (hUser.jsUser.gender == "F") $("profile_gender").setHTML("Female");
			if (hUser.jsUser.gender == "M") $("profile_gender").setHTML("Male");
		}
		if ($defined($("profile_location"))) $("profile_location").setHTML(hUser.jsUser.location);
		if ($defined($("profile_dob"))) $("profile_dob").setHTML(hUser.jsUser.dob);
		if ($defined($("profile_msn"))) $("profile_msn").setHTML(hUser.jsUser.msn);
		if ($defined($("profile_intro"))) $("profile_intro").setHTML(hUser.jsUser.intro);
		if ($defined($("profile_allow_search"))){
			$("profile_allow_search").setHTML( (hUser.jsUser.allow_search == "Y")? "Yes":"No" );
		}
		if ($defined($("profile_email_notify"))){
			$("profile_email_notify").setHTML( (hUser.jsUser.email_notify == "Y")? "Yes":"No" );
		}
		if ($defined($("profile_newsletter"))){
			$("profile_newsletter").setHTML( (hUser.jsUser.newsletter == "Y")? "Yes":"No" );
		}
		if (fn) fn();
		//console.log(hUser.jsUser);
	}
}

var hTips = {
	init : function(){
		var tipEl = $$("span[tag=tips]");
		var tips = new Tips(tipEl);
	}
}

var hCookies = {
	autoHelp : function(){
		return Cookie.get("autohelp");
		// 0 = null, 1 = yes, 2 = no
	},
	init : function(){
		this.Sync.syncAutoHelp();
		this.Setter.init();
	},
	Sync : {
		syncAutoHelp : function(){
			if ($defined($("tips_control"))){
				if (hCookies.autoHelp() <= 1){
					$("tips_control").setProperty("checked", "checked");
					Cookie.set("autohelp", 1);
				}
			}
		}
	},
	Setter : {
		init : function(){
			if ($defined($("tips_control"))){
				$("tips_control").addEvent("click", function(){
					if (Cookie.get("autohelp") == 1){
						Cookie.set("autohelp", 2);
					} else Cookie.set("autohelp", 1);
				});
			}
		},
		setAutoHelp : function(){
		}
	}
}

var hSearch = {
	flag : true,
	menu : {
		init : function(){
			var szNormal = 160, szSmall  = 100, szFull   = 345;
			var kwicks = $$("#search_menu li");
			var fx = new Fx.Elements(kwicks, {wait: false, duration: 300, transition: Fx.Transitions.Back.easeOut});

			kwicks.each(function(kwick, i) {
					kwick.addEvent("mouseenter", function(event) {
						
						if (hSearch.flag){
							var o = {};
							o[i] = {width: [kwick.getStyle("width").toInt(), szFull]}
							kwicks.each(function(other, j) {
								if(i != j) {
									var w = other.getStyle("width").toInt();
									if(w != szSmall) o[j] = {width: [w, szSmall]};
								}
							});			
						fx.start(o);
						}
					});
				});				

			kwicks.each(function(kwick, i) {
					kwick.addEvent("mouseleave", function(event) {
						if (hSearch.flag){
							var o = {};
							kwicks.each(function(kwick, i) {
								o[i] = {width: [kwick.getStyle("width").toInt(), szNormal]}
							});
							fx.start(o);
						}
					});
				});

			$("location").addEvent("focus", function(event) {
				hSearch.flag = false;
			});
			
			$("location").addEvent("blur", function(event) {
				$("location").blur();
				hSearch.flag = true;
				kwicks.each(function(kwick, i) {kwick.fireEvent("mouseleave")});
			});
			
			$("location").addEvent("change", function(event) {
				$("location").fireEvent("blur");
				$$("#location option").each(function(e, i){
					if (e.selected)	$("location_display").innerHTML = e.getProperty("fullname");
				});
			});
			
			$("gender").addEvent("focus", function(event) {
				hSearch.flag = false;
			});
			
			$("gender").addEvent("blur", function(event) {
				$("gender").blur();
				hSearch.flag = true;
				kwicks.each(function(kwick, i) {kwick.fireEvent("mouseleave")});							
			});
			
			$("gender").addEvent("change", function(event) {
				
				$$("#gender option").each(function(e, i){
					if (e.selected)	$("gender_display").innerHTML = e.innerHTML;
				});
				$("gender").fireEvent("blur");
			});
			
				$("age").addEvent("focus", function(event) {
				hSearch.flag = false;
			});
			
			$("age").addEvent("blur", function(event) {
				$("age").blur();
				hSearch.flag = true;
				kwicks.each(function(kwick, i) {kwick.fireEvent("mouseleave")});							
			});
			
			$("age").addEvent("change", function(event) {
				$("age").fireEvent("blur");
				$$("#age option").each(function(e, i){
					if (e.selected)	$("age_display").innerHTML = e.innerHTML;
				});
			});
		}	
	},
	search :{
		cache: null,
		submitSearch : function(isNew, start, count){
			if (gBlocking) return false;
			gBlocking = true;
			var fx = new Fx.Style("search_result", "opacity", {
				wait: false
			});
			var query = $("search_form");
			if (isNew) query = query.toQueryString() + "&isNew=1";
			else query = query.toQueryString() + "&start_index=" + start + "&max_element=" + count;
			var searchAjax = new Ajax("SearchControl.php", {
				data: query,
				onRequest: function(){
				},
				onComplete: function(data){
					var reply = Json.evaluate(data, true);
					hSearch.result = reply.user;
					//hSearch.updateNumbers(reply);
					$("search_div").setStyle("display", "block");
					$("search_result").setHTML(reply.html);
					fx.start(1);
					hSearch.search.cache = reply.html;
					hTips.init();
					gBlocking = false;
				}
			}).request();
			fx.start(0);
		}
	},
	updateNumbers : function(jReply){
		/*$("search_start").setHTML(jReply.search_start);
		$("search_max").setHTML(jReply.search_max);
		$("search_total").setHTML(jReply.search_total);
		$("search_limit").setHTML(jReply.search_limit);*/
	},
	result : null
}

var hMessage = {
	target : {
		name : "",
		id : "",
		photo : ""
	},
	mailbox : 0, // 0 = inbox, 1 = outbox
	div : "msg_div",
	reply : null,
	deleteId : null,
	utility : {
		syncMessageCounter : function(){
		},
		unboldOldMessage : function(){
			var msg = $$("span[tag=old]");
			msg.each(function(el){
				el.setStyle("fontWeight", "normal");
			});
		},
		initHover : function(){
			if (!window.ie6) return false;
			var msg = $$("span[class=message_container]");
			msg.each(function(el){
				el.addEvent("mouseenter", function(){
					el.setStyle("color", "white").setStyle("background-image", "url(res/common/images/message_highlight.jpg)");
				});
				el.addEvent("mouseleave", function(){
					el.setStyle("color", "black").setStyle("background-image", "none");
				});
			});
		}
	},
	window : {
		getWindow : function(which, id){
			if (hSearch.result) hMessage.target = hSearch.result[id];
			//console.log(hMessage.target);
			switch(which){
				case("send"): hMsg.getData("getsendmessagewindow");
					break;
				default: break;
			}
		},
		fillWindow : function(){
			if ($defined($("message_sendto_id"))) $("message_sendto_id").setProperty("value", hMessage.target.id);
			if ($defined($("message_sendto_name"))) $("message_sendto_name").setHTML(hMessage.target.name);
			if ($defined($("message_sendto_photo"))) $("message_sendto_photo").setProperty("src", hMessage.target.photo+".tn.jpg");
		},
		goInbox : function(){
			hMessage.mailbox  =  0;
			//$(hMessage.div).setHTML("inbox");
			var outboxAjax = new Ajax("MessageControl.php", {
				method: "post",
				data : {					
					action: "getinboxmessage"
				},
				update : $(hMessage.div),
				onComplete : function(){
					hMessage.utility.unboldOldMessage();
					hMessage.utility.initHover();
					$("message_box_name").setHTML(hTranslation.Message.Inbox);
				},
				onFailure : function(){
					outboxAjax.request();
				}
			}).request();
		},
		goOutbox : function(){
			hMessage.mailbox  =  1;
			//$(hMessage.div).setHTML("outbox");
			var outboxAjax = new Ajax("MessageControl.php", {
				method: "post",
				data : {					
					action: "getoutboxmessage"
				},
				update : $(hMessage.div),
				onComplete : function(){
					hMessage.utility.unboldOldMessage();
					hMessage.utility.initHover();
					//console.log("outbox");
					$("message_box_name").setHTML(hTranslation.Message.Outbox);
				},
				onFailure : function(){
					inboxAjax.request();
				}
			}).request();
		}
	},
	send : function(){
		var sendAjax = new Ajax("MessageControl.php", {
			method: 'post',
			data: $("message_send_form"),
			onComplete: function(data){
				//console.log(data);
				hMsg.hide();
			}
		});
		if ($$("textarea[name=message_sendto_content]")[0].getValue().length>0) sendAjax.request();
	},
	read : function(el, msg_id){
		//if (!window.ie6) el.setProperty("tag", "old");
		//else el.tag = "old";
		el.tag = "old";
		hMessage.reply = msg_id;
		hMessage.utility.unboldOldMessage();
		hMessage.target.name = el.getProperty("msg_from");
		hMessage.target.id = el.getProperty("msg_userid");
		hMessage.target.photo = el.getProperty("msg_photo");
		hMsg.getData("getmessagebyid");
	},
	remove : function(){
		var deleteAjax = new Ajax("MessageControl.php", {
			method: 'post',
			data : {
				action: "delete",
				id: hMessage.deleteId
			},
			onComplete : function(){
				var str = "span[msg_id="+hMessage.deleteId+"]";
				//console.log($$(str)[0]);
				$$(str)[0].remove();
				hMsg.hide();
			}
		}).request();
	},
	confirmDelete : function(evt, id){
		var e = new Event(evt);
		e.stopPropagation();
		e.preventDefault();
		hMessage.deleteId = id;
		hMsg.getData("confirmdelete");
	}
}

var hSequence = {
	hComWin : null,
	editing : false,
	target : {
		name : "",
		id : "",
		photo : ""
	},
	mailbox : 0, // 0 = inbox, 1 = outbox
	div : "msg_div",
	reply : null,
	deleteID : null,
	utility : {
		syncMessageCounter : function(){
		},
		unboldOldMessage : function(){
			var msg = $$("span[tag=old]");
			msg.each(function(el){
				el.setStyle("fontWeight", "normal");
			});
		},
		initHover : function(){
			if (!window.ie6) return false;
			var msg = $$("span[class=message_container]");
			msg.each(function(el){
				el.addEvent("mouseenter", function(){
					el.setStyle("color", "white").setStyle("background-image", "url(res/common/images/message_highlight.jpg)");
				});
				el.addEvent("mouseleave", function(){
					el.setStyle("color", "black").setStyle("background-image", "none");
				});
			});
		}
	},
	window : {
		getWindow : function(which, id){
			if (hSearch.result) hMessage.target = hSearch.result[id];
			//console.log(hMessage.target);
			switch(which){
				case("send"): hMsg.getData("getsendmessagewindow");
					break;
				default: break;
			}
		},
		fillWindow : function(){
			if ($defined($("message_sendto_id"))) $("message_sendto_id").setProperty("value", hMessage.target.id);
			if ($defined($("message_sendto_name"))) $("message_sendto_name").setHTML(hMessage.target.name);
			if ($defined($("message_sendto_photo"))) $("message_sendto_photo").setProperty("src", hMessage.target.photo+".tn.jpg");
		},
		goInbox : function(){
			hMessage.mailbox  =  0;
			//$(hMessage.div).setHTML("inbox");
			var outboxAjax = new Ajax("MessageControl.php", {
				method: "post",
				data : {					
					action: "getinboxmessage"
				},
				update : $(hMessage.div),
				onComplete : function(){
					hMessage.utility.unboldOldMessage();
					hMessage.utility.initHover();
					$("message_box_name").setHTML(hTranslation.Message.Inbox);
				},
				onFailure : function(){
					outboxAjax.request();
				}
			}).request();
		},
		goOutbox : function(){
			hMessage.mailbox  =  1;
			//$(hMessage.div).setHTML("outbox");
			var outboxAjax = new Ajax("MessageControl.php", {
				method: "post",
				data : {					
					action: "getoutboxmessage"
				},
				update : $(hMessage.div),
				onComplete : function(){
					hMessage.utility.unboldOldMessage();
					hMessage.utility.initHover();
					//console.log("outbox");
					$("message_box_name").setHTML(hTranslation.Message.Outbox);
				},
				onFailure : function(){
					inboxAjax.request();
				}
			}).request();
		}
	},
	send : function(){
		var sendAjax = new Ajax("MessageControl.php", {
			method: 'post',
			data: $("message_send_form"),
			onComplete: function(data){
				//console.log(data);
				hMsg.hide();
			}
		});
		if ($$("textarea[name=message_sendto_content]")[0].getValue().length>0) sendAjax.request();
	},
	read : function(el, msg_id){
		if (!window.ie6) el.setProperty("tag", "old");
		else el.tag = "old";
		hMessage.reply = msg_id;
		hMessage.utility.unboldOldMessage();
		hMessage.target.name = el.getProperty("msg_from");
		hMessage.target.id = el.getProperty("msg_userid");
		hMessage.target.photo = el.getProperty("msg_photo");
		hMsg.getData("getmessagebyid");
	},
	remove : function(){
		var deleteAjax = new Ajax("SequenceControl.php", {
			method: 'post',
			data : {
				action: "deletesequence",
				sid: hSequence.deleteID
			},
			onComplete : function(){
				$$("div[sid="+hSequence.deleteID+"]")[0].remove();
				//$("sequence_"+hSequence.deleteID).remove();
				hMsg.hide();
			}
		}).request();
	},
	confirmDelete : function(evt, id){
		var e = new Event(evt);
		e.stopPropagation();
		e.preventDefault();
		/*hMessage.deleteId = id;
		hMsg.getData("confirmdelete");*/
		if (hSequence.editing) {
			hMsg.getData("nodelete");
		} else {
			hSequence.deleteID = id;
			hMsg.getData("confirmdelete0");
		}
	},
	create : function(){
		if (window.ie7 || window.gecko){
			// open a pop up window here
			this.hideTips();
			this.hComWin = window.open('composer.php', 'composer', 'location=no,titlebar=no,resizable=yes,height=480,width=900', false);
			this.hComWin.focus();
		}
		else {
			hMsg.getData("needupdate");
		}
	},
	edit : function(id){
		// check browser
		if (window.ie7 || window.gecko){
			// open a pop up window here
			this.hideTips();
			this.hComWin = window.open('composer.php?sid=' + id, 'composer', 'location=0,resizable=yes,height=480,width=900', false);
			this.hComWin.focus();
		}
		else {
			hMsg.getData("needupdate");
		}
	},
	refresh : function(){
		this.hideTips();
		if (section=="sequence") getMainPane("getsequencetemplate", "SequenceControl.php", "post", function(data){});
	},
	hideTips : function(){
		$$("div.tool-tip").each(function(d){
			d.setStyle("visibility", "hidden");
		});
	},
	play : function(id){
		$("sq_dummy").src = "ucibp://sp" + id;
	},
	download : function(id){
		$("sq_dummy").src = "ucibp://sd" + id;
		// added
		/*tag = $$("div[sid="+id+"]")[0];
		path = tag.getProperty("buddytag");
		if (path == "0"){
			return false;
		} else {
			// open an ajax to log download
			var statAjax = new Ajax("SequenceControl.php", {
				method: "post",
				data: {
					"action" : "logdownload",
					"sq_path" : path
				}
			}).request();
		}*/
		//
	},

	getEmoticon : function(id){
		tag = $$("div[sid="+id+"]")[0];
		path = tag.getProperty("buddytag");
		if (path == "0"){
			return false;
		} else {
			$("sq_dummy").src = path;
			if (window.ie){
				emoticon = $$("img[tag=emoticon]");
				(function(){emoticon.each(function(el){	
					tmp = el.src;
					el.src = "";
					el.src = tmp;
				});}).delay(1000);
			}
			// open an ajax to log download
			var statAjax = new Ajax("SequenceControl.php", {
				method: "post",
				data: {
					"action" : "logdownload",
					"sq_path" : path
				}
			}).request();
		}
	},
	uploadImage : function(id){
		// to be implemented
	},
	publishToggle : function(id){
		box = $("sq_publish_"+id);
		box.setProperty("disabled", "disabled");
		flag = box.getProperty("checked");
		pubishAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : {
				"action" : "togglepublish",
				"sq_id" : id,
				"publish_flag" : flag
			},
			onComplete : function(reply){
				if (reply == "1"){
					if (!flag) box.removeProperty("checked");
					else box.setProperty("checked", "checked");
				}
				box.removeProperty("disabled");
			}
		}).request();
		return false;
	},
	forcePublish : function(id){
		box = $("sq_publish_"+id);
		box.setProperty("disabled", "disabled");
		flag = box.getProperty("checked");
		pubishAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : {
				"action" : "togglepublish",
				"sq_id" : id,
				"publish_flag" : true
			},
			onComplete : function(reply){
				/*if (reply == "1"){
					if (!flag) box.removeProperty("checked");
					else box.setProperty("checked", "checked");*/
					box.setProperty("checked", "checked");
					box.removeProperty("disabled");
				//}
				//box.removeProperty("disabled");
			}
		}).request();
		return false;
	},
	reloadImage : function(id, url, durl){
		el = $("emoticon_img_" + id);
		el.src = "";
		el.src = url + "&ts=" + new Date().getTime();
		el = $("emoticon_upload_frame_" + id);
		el.src = "src/html/core/upload_emoticon.php?sq_id=" + id;
		tag = $$("div[sid="+id+"]")[0];
		tag.setProperty("buddytag", durl);
	},
	echoUploadError : function(id, eCode){
		el = $("emoticon_upload_frame_" + id);
		el.src = "src/html/core/upload_emoticon.php?sq_id=" + id;
		hMsg.fillData("SequenceControl.php", "get", {
			"action" : "getuploaderror",
			"errorcode" : eCode
		}, null);
	},
	goSearch : function(){
		new Ajax("SequenceControl.php", {
			method : "post",
			data : {
				action : "getsequencelistingtemplate"
			},
			onComplete : function(reply){
				$("first_pane").setHTML(reply);
				//hSequence.searchSequence();
			}
		}).request();
	},
	goMySequence : function(){
		sqMyAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : {
				action : "getmysequencelisting"
			},
			onComplete : function(reply){
				$("first_pane").setHTML(reply);
			}
		}).request();
	},
	goInstruction : function(){
		new Ajax("SequenceControl.php", {
			method : "post",
			data : {
				action : "getinstruction"
			},
			onComplete : function(reply){
				$("first_pane").setHTML(reply);
			}
		}).request();
	},
	searchByDL : function(){
		options =  $$("select[name=sort]")[0].getElements("option");
		options.each(function(o){
			if (o.value == 1) o.setProperty("selected", "selected");
			else o.removeProperty("selected");
		});
		sqSearchAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : $("sq_search_form"),
			onComplete : function(reply){
				$("sq_listing_div").setHTML(reply);
				$("searchBar").setStyle("display", "");
			}
		}).request();
	},
	searchByUT : function(){
		options =  $$("select[name=sort]")[0].getElements("option");
		options.each(function(o){
			if (o.value == 2) o.setProperty("selected", "selected");
			else o.removeProperty("selected");
		});
		sqSearchAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : $("sq_search_form"),
			onComplete : function(reply){
				$("sq_listing_div").setHTML(reply);
				$("searchBar").setStyle("display", "");
			}
		}).request();
	},
	searchSequence : function(){
		sqSearchAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : $("sq_search_form"),
			onComplete : function(reply){
				$("sq_listing_div").setHTML(reply);
				$("searchBar").setStyle("display", "");
			}
		}).request();
		return false;
	},
	page : function(startIndex){
		$("sq_page_start").setProperty("value", startIndex);
		sqSearchAjax = new Ajax("SequenceControl.php", {
			method : "post",
			data : $("sq_page_form"),
			onComplete : function(reply){
				$("sq_listing_div").setHTML(reply);
			}
		}).request();
		return false;
	},
	syncSearchControl : function(){
	}
}

var hMember = {
	next : function(){
		if ($defined($("new_member"))){
			iAjax = new Ajax("src/controller/ContentControl.php", {
				method : "get",
				data : {
					action : "getnextmember"
				},
				onComplete : function(data){
					var reply = Json.evaluate(data, true);
					$("new_member").src = reply.photo;
					$("member_name").setHTML(reply.name);
					$("member_text").setHTML(reply.desc);
					$("member_from").setHTML(reply.from);
					//<span style="float: right; font-weight: bold; color: #aa6633">From France</span>
					
				}
			}).request();
		}
	}
}

var hECard = {
	resultWin : null,
	send : function(){
		if (hECard.validate()){
			preview = new Ajax("ecard.php?action=send", {
				method : "post",
				data : $("ecard_form"),
				onRequest : function(){
					$("ecard_form").getElements("input").each(function(el){
						el.setProperty("disabled", "disabled");
					});
				},
				onComplete : function(data){
					//$("ecard_form").reset();
					$("ecard_form").getElements("input").each(function(el){
						el.removeProperty("disabled");
					});
					if (confirm("The card has been sent! Do you want to view it?")){
						hECard.resultWin = window.open(data, 'e_preview', 'location=no,titlebar=no,resizable=yes,height=450,width=350', false);
						hECard.resultWin.focus();
					}
				}
			}).request();
		}
	},
	preview : function(){
		if (hECard.validate()){
			preview = new Ajax("ecard.php?action=preview", {
				method : "post",
				data : $("ecard_form"),
				onRequest : function(){
					$("ecard_form").getElements("input").each(function(el){
						el.setProperty("disabled", "disabled");
					});
				},
				onComplete : function(data){
					$("ecard_form").getElements("input").each(function(el){
						el.removeProperty("disabled");
					});
					hECard.resultWin = window.open(data, 'e_preview', 'location=no,titlebar=no,resizable=yes,height=450,width=350', false);
					hECard.resultWin.focus();
				}
			}).request();
		}
	},
	validate : function(){
		if (!$("name").value.trim().match(/^.+$/)){
			alert("You must enter your name");
			return false;
		}
		if (!$("target_email").value.trim().match(/^(\w(.?)+)@(\w(.?)+)\.(\w+)$/i)){
			alert("Invalid receiver email address entered.");
			return false;
		}
		if (!$("sender_email").value.trim().match(/^(\w(.?)+)@(\w(.?)+)\.(\w+)$/i)){
			alert("Your email address is invalid");
			return false;
		}
		return true;
	}
}

var hLoginCookie = {
	rememberLogin : function(login, password){
		Cookie.set("username", login, {duration: 30});
		Cookie.set("password", "", {duration: 30});
	},
	
	forgetLogin : function(){
		Cookie.remove("username");
		Cookie.remove("password");
		if ($defined($("remember_me"))){
			$("remember_me").removeProperty("checked");
			$("input_login").value = "";
			$("input_password").value = "";
		}
	},
	
	fillLogin : function(){
		if (Cookie.get("username")){
			$("input_login").value = Cookie.get("username");
		}
		
		if (Cookie.get("password")){
			$("input_password").value = Cookie.get("password");
		}
	}
}

// IE 7 Flash Fix
function fixFlash(){
	objects = document.getElementsByTagName("object");
	for (var i = 0; i < objects.length; i++){
		objects[i].outerHTML = objects[i].outerHTML;
	}
}

// Utility
function alignPaneTo(pane1, pane2, offset){
	if (!$defined(pane1) || !$defined(pane2)) return false;
	var h1 = pane1.getSize().size.y;
	var h2 = pane2.getSize().size.y;
	if (h2>h1) pane1.setProperty("height", h2+offset).setStyle("height", h2+offset);
}

function alignTile(pane, height, offset){
	if (!$defined(pane)) return false;
	var h = pane.getSize().scrollSize.y;
	var multiplyer =  Math.floor(h/height) + 1;
	pane.setStyle("height", multiplyer*height+offset);
}

function getTileHeight(pane, tileHeight, offset){
	if (!$defined(pane)) return 0;
	var h = pane.getSize().scrollSize.y;
	var multiplyer = Math.floor(h/tileHeight) + 1;
	return (multiplyer*tileHeight + offset);
}

function setDrag(){
	var oldx, oldy;
	$("msg_handle").setStyle("cursor", "move");
	var myDrag = new Drag.Base($("msg_window"), {
		handle: $("msg_handle"),
		onStart: function(e){
			oldx = e.getStyle("left");
			oldy = e.getStyle("top");
		},
		onComplete: function(e){
			var fx = new Fx.Styles($("msg_window"), {
				duration: 500,
				transition: new Fx.Transition(Fx.Transitions.Elastic.easeOut)
			});
			fx.start({
				left : oldx,
				top : oldy
			});
		}
	});
}

var screenCenter = {
	x : function(){
		return (window.getWidth()/2);
	},
	
	y : function(){
		return (window.getHeight()/2);
	}
}

var utility = {
	hideFlash: function(){
		var flash = $$("div[id=flash_container]");
		flash.each(function(el){
			el.setStyle("visibility", "hidden");
		});
	},
	showFlash: function(){
		var flash = $$("div[id=flash_container]");
		flash.each(function(el){
			el.setStyle("visibility", "visible");
		});
	}
}

function centerElement(el){
	var h = el.getSize().scrollSize.y;
	var w = el.getSize().scrollSize.x;
	
	el.setStyle("top", screenCenter.y() - h/2).setStyle("left", screenCenter.x() - w/2);
}

function hideSubMenu(onComplete){
	var smTab = $("sub_pane");
	if ($defined(onComplete)) var fx = new Fx.Styles(smTab, {
		duration: 400,
		wait: false,
		//transition: new Fx.Transition(Fx.Transitions.Bounce.easeOut),
		onComplete: onComplete
	});
	else var fx = new Fx.Styles(smTab, {
		wait: true,
		duration: 400
		//transition: new Fx.Transition(Fx.Transitions.Bounce.easeOut)
	});
	fx.start({
		height: 0
	});
}

function showSubMenu(onComplete){
	var smTab = $("sub_pane");
	if ($defined(onComplete)) var fx = new Fx.Styles(smTab, {
		wait: true,
		duration: 800,
		transition: new Fx.Transition(Fx.Transitions.Bounce.easeOut),
		onStart: function(){
			},
		onComplete: onComplete
	});
	else var fx = new Fx.Styles(smTab, {
		wait: true,
		duration: 800,
		transition: new Fx.Transition(Fx.Transitions.Bounce.easeOut)
	});
	fx.start({
		height: getTileHeight($("sub_pane"), 61, -14)
	});
}

function goBuy(){
	$('btn_buy').fireEvent('click');
	(function(){$('btn_buy').fireEvent("mosueenter")}).delay(100);
}

// Animator
function enableAnimation(){
	var animDiv = $$("div[js=anim]");
	animDiv.each(function(div){
		var frame = div.getProperty("w")/100;
		var anim = function(){
			div.setStyle("background-position", div.getStyle("background-position").toInt()+100);
		};
		var play;
		div.addEvent("mouseenter", function(){
			anim();
			play = anim.periodical(div.getProperty("s").toInt());
		});
		div.addEvent("mouseleave", function(){
			$clear(play);
		});
	});
}

// Menu Retrieving
function getSubPane(which){

	var tweenPanelDefault = true;
	if (hUser.login && which=="getloginbox"){
		which="getuserpanel";
		tweenPanelDefault = false;
	}

	var menu = new Ajax("src/controller/LayoutControl.php", {
		method: 'get',
		link: "wait",
		data: {
			action: which,
			ts : new Date().getTime()
		},
		onComplete: function(data){
			$("sub_pane").setHTML(data);				
			if (!window.opera){
				if ($defined($("opera_hack"))) $("opera_hack").remove();
			}
			initSubMenu();
			hInput.initButton();
			showSubMenu(function(){
				 switch(which){
					case("getproductmenu"):
						tweenMenuItem($("product_what"));
						break;
					case("getloginbox"):
						hLogin.initLoginForm();
						// fill rem me
						if (Cookie.get("username")){// && Cookie.get("password")){
							$("remember_me").checked = "checked";
							$("input_login").value = Cookie.get("username");
							$("input_password").value = Cookie.get("password");
						}
						break;
					case("getuserpanel"):
						hUser.initPanel();
						break;
					default:
						break;
				 }
			});
		}
	});
	hideSubMenu(function(){
		menu.request();
	});
}

// Page Serving
function getMainPane(which, php, mth, fn){
	var phpurl = "src/controller/ContentControl.php";
	var get_or_post = "get";
	if (php) phpurl = php;
	if (mth) get_or_post = mth;
//alert(which);
	
	var pane = new Ajax(phpurl, {
		method: get_or_post,
		data: {
			action: which,
			ts: new Date().getTime(),
			lang : language
		},
		onRequest: function(){
			$("ajax_content").effects("opacity", 0.01);
		},
		onComplete: function(data){
			$("ajax_content").setOpacity(0).setHTML(data);
			if ($defined($("flash_container")))	$("flash_container").setStyle("visibility", "hidden");
			if (window.ie7 || window.opera) fixFlash();
			if (section == "register"){
				hReg.initRegForm();
			}
			alignPaneTo($("first_pane"), $("second_pane"), -75);
			switch(which){
				case("getprofile"):
					hProfile.initAccord();
					hTips.init();
					/*if (hCookies.autoHelp() < 2){
						gBlocking = true;
						(function(){
							hMsg.getData("profilehelp")
							gBlocking = false;
						}).delay(1500);
					}*/
					break;
				case("getsearchtemplate"):
					break;
				case("getmessagetemplate"):
					break;
				case("getsequencetemplate"):
					hTips.init();
					break;
				case("getdistributor"):
						var aHeads = $$("div[class=main_accord]");
						var aContents = $$("div[class=accord_content]");
						var accord = new Accordion(aHeads, aContents, {
							opacity : false,
							alwaysHide : true,
							display :null
						}, $('accordion'));
						(function(){$$("div[class=main_accord]")[0].fireEvent("click")}).delay(200);
					break;
				default:break;
			}
			var fx = new Fx.Style("ajax_content", "opacity", {
				onComplete: function(){
					alignPaneTo($("first_pane"), $("second_pane"), -75);
					if ($defined($("flash_container")))	$("flash_container").setStyle("visibility", "visible");
					$("blocker").setStyle("display", "none")
					enableAnimation();
				}
			}).start(1);
			if (fn) fn(data);
		}
	});
	$("blocker").setStyle("display", "block").setOpacity(0.01).setStyle("width", window.getScrollWidth()).setStyle("height", window.getScrollHeight());
	pane.request();
}

function servePage(which){
	switch(which){
		case("home"):
			getSubPane("getloginbox");
			getMainPane("gethome");
			break;
		case("product"):
			getSubPane("getproductmenu");
			break;
		case("contact"):
			getSubPane("getcontactmenu");
			getMainPane("getcontact");
			break;
        case("api"):
			getSubPane("getcontactmenu");
			getMainPane("getapi");
			break;
		case("iwantthis"):
			getSubPane("getcontactmenu");
			getMainPane("getiwantthis");
			break;
		case("register"):
            //url = "http://community.i-buddy.com/?r=user/register";
   //         url = "?r=user/register";
            sn = window.location.href.match(/key=.{16}/i);
            // if (sn != null){
                // url = url + '&' + sn;
                // window.location.href = url;
            // }
            // else {
                // j = window.open(url);
                // j.focus();
            // }
            // return;
            
			// getSubPane("getcontactmenu");
			//getMainPane("getregister");
			getMainPane("goregister", "regControl.php", "get", null);
			section = "register";
			var menuitems = $$("span[class=menu_item]");
			menuitems.each(function(el){
				el.setProperty("active", "false");
				el.fireEvent("mouseleave");
			});
			break;
		case("buy"):
			getSubPane("getcontactmenu");
			getMainPane("getdistributor");
			break;
		case("community"):
			getSubPane("getuserpanel");
			getMainPane("getprofile", "ProfileControl.php", "post");
			break;
		case("search"):
			getMainPane("getsearchtemplate", "SearchControl.php", "post");
			break;
		case("debug"):
			break;
		case("download"):
			getMainPane("getdownloadtemplate");
			//console.log("download");
			break;			
		default:
			getSubPane("getloginbox");
			break;
	}
}

function initSubMenu(){
	var smitems = $$("#sub_menu li");
	smitems.each(function(el){
		el.setProperty("active", "false");
		el.setStyle("cursor", "pointer");
		var fx = new Fx.Styles(el, {
			wait : false,
			duration : 1000,
			transition: new Fx.Transition(Fx.Transitions.Bounce.easeOut)
		});
		var fxBg = new Fx.Styles(el, {
			wait : false,
			duration : 400
		});
		el.addEvent("mouseenter", function(){
			fx.start({
				"padding-left": 60,
				wait: true
			});
			fxBg.start({
				"background-color": "#412C1C",
				"color": "#ffffff",
				wait: true
			});
		});
		el.addEvent("mouseleave", function(){
			if (el.getProperty("active") == "false"){
				fx.start({
					"padding-left": 15
				});
				fxBg.start({
					"background-color": "#eacd7e",
					"color": "#412C1C"
				});
			}
		});
		el.addEvent("click", function(){			
			// define sub menu actions
			switch(el.getProperty("id")){
				case("product_what"):
					if (el.getProperty("active") == "false"){
						getMainPane("getproductwhat");
					}
					break;
				case("product_how"):
					if (el.getProperty("active") == "false"){
						getMainPane("getproducthow");
					}
					break;
				case("product_can"):
					if (el.getProperty("active") == "false"){
						getMainPane("getproductdemo");
					}
					break;				
				case("product_detail"):
					if (el.getProperty("active") == "false"){
						getMainPane("getproductdetail");
					}
					break;
				default: break;
			}
			
			el.setProperty("active", "true");
			fx.stop();
			fxBg.stop();
			smitems.each(function(e){
				if ((e != el)&&(e.getProperty("active") == "true")){
					e.setProperty("active", "false");
					e.fireEvent("mouseleave");
				}
			});
			el.fireEvent("mouseenter");
		});
	});
}

function tweenMenuItem(which){
	if (!$defined(which)) return false;
	which.fireEvent("click");
}

window.addEvent("load", function(){
	
	var fx = new Fx.Style("loader", "opacity", {
		duration: 500,
		onComplete: function(){			
			}
	}).start(1).chain(
		function(){
			$("loader").setHTML("");
			var fx0 = new Fx.Style("loader", "opacity", {
				duration: 1000,
				onComplete: function(){
					$("loader").remove();
					$("content").setStyle("display", "block");
					alignPaneTo($("first_pane"), $("second_pane"), -90);
					if (hUser.login) section = "community";				
					
					switch(section){
						case("home"):
							servePage("home");
							break;
						case("product"):
							servePage("product");
							break;
						case("community"):
							servePage("community");
							break;
						case("register"):
							servePage("register");
							break;
						case("iwantthis"):
							servePage("iwantthis");
							break;
                        case("api"):
                            servePage("api");
                            break;
						default:
							break;
					}
				}
			}).start(0);
		}
	);
});

window.addEvent("domready", function(){    

	//console.log($$("#lang_select", "option"));
	$$("#lang_select", "option").each(function(el){
		if (el.value == language){
			el.setProperty("selected", "selected");
		}
	});

	$("lang_select").addEvent("change", function(v){
		window.location.href = "http://www.i-buddy.com/index.php?lang=" + this.getValue();
	});
									 
	centerElement($("loader"));
	$("loader").setStyle("display", "block");
	
	// Retrieve session user
	hUser.getSessionUser();
	
	// Recenter the message box div when resize and/or scroll
	window.addEvent("resize", function(){
		if ($defined($("loader"))) centerElement($("loader"));
		hMsg.center();
		$("blocker").setStyle("width", window.getScrollWidth()).setStyle("height", window.getScrollHeight());
	});
	
	window.addEvent("scroll", function(){
		if ($defined($("loader"))) centerElement($("loader"));
		hMsg.center();
	});
	
	document.addEvent("keyup", function(e){
		var evt = new Event(e);
		if (evt.key == "esc"){
			if (hMsg.showing) hMsg.hide();
		}
	});
	
	document.addEvent("keydown", function(e){
		/*var evt = new Event(e);
		if ( (evt.code>=33 && evt.code<=40) ){
			if (hMsg.showing){
				evt.stopPropagation();
				evt.preventDefault();
			}
		}*/
	});
	
	// Change the behvaior of the CSS depends on the browser
	if (window.ie7 || window.gecko || window.webkit420) {
		$("msg_bg").setStyle("backgroundImage", "url(res/en-us/css/blue/big_box_tile.png)").setStyle("backgroundRepeat", "repeat-y");
		//$("right_pane").setStyle("padding-bottom", 32767).setStyle("margin-bottom", -32767);
	}
	else {
		$("blocker").setStyle("position", "absolute");
		$("msg_window").setStyle("position", "absolute");		
	}
	
	// Focuser initialization
	$("focuser").setOpacity(0);
					 
	// Define object message window
	hMsg = {
		/* properties */
		div : $("msg_window"),
		blocker : $("blocker"),
		focuser : $("focuser"),
		showing : false,
			
		/* public functions */
		center : function(){
			x = screenCenter.x() - this.getDivSize().width/2;
			y = screenCenter.y() - this.getDivSize().height/2;
			if (!window.ie7 && !window.gecko && !window.webkit420){
				x += window.getScrollLeft();
				y += window.getScrollTop();
			}
			this.div.setStyle("top", y).setStyle("left", x);
			return this.div;
		},
		
		fillData : function(url, mth, param, fn){
			var get_or_post = "get";
			if (mth) get_or_post = mth;
			var getAjax = new Ajax(url, {
				method: get_or_post,
				data: param,
				onComplete: function(data){
					$("msg_data").setHTML(data);
					if ($defined($("close_msg_box"))){
						$("close_msg_box").addEvent("click", function(){
							hMsg.hide();
						});
					}
					hCookies.init();
					hMsg.show();
					if (fn) fn();
				}
			}).request();
		},
		
		getData : function(which){
			switch(which){
				case("gocommunity"):
					// res/"+ language +"
					this.fillData("res/"+ language +"/template/community/oldsite.tpl");
					break;
				case("profilehelp"):
					this.fillData("res/"+ language +"/template/community/profile_help.tpl");
					break;
				case("regerror"):
					this.fillData("res/"+ language +"/template/community/regerror.tpl");
					break;
				case("loginfailed"):
					this.fillData("res/"+ language +"/template/login/loginfailed.tpl");
					break;
				case("loginrequired"):
					this.fillData("res/"+ language +"/template/login/loginrequired.tpl");
					break;
				case("forgetpassword"):
					this.fillData("res/"+ language +"/template/login/forgetpassword.tpl");
					break;
				case("forgetpassword_failed"):
					this.fillData("res/"+ language +"/template/login/forgetpassword_failed.tpl");
					break;
				case("forgetpassword_succeed"):
					this.fillData("res/"+ language +"/template/login/forgetpassword_succeed.tpl");
					break;
				case("confirmlogout"):
					this.fillData("res/"+ language +"/template/login/confirm_logout.tpl");
					break;
				case("printlogout"):
					this.fillData("res/"+ language +"/template/login/logged_out.tpl");
					break;
				case("loginrequired"):
					this.fillData("res/"+ language +"/template/login/login_notice.tpl");
					break;
				case("editprofilegeneral"):
					this.fillData("ProfileControl.php", "post", {action: "geteditgeneral"}, function(){
						hProfile.initCalendar();
					});
					break;
				case("editprofileintro"):
					this.fillData("ProfileControl.php", "post", {action: "geteditintro"}, function(){						
					});
					break;
				case("editprofilepreferences"):
					this.fillData("ProfileControl.php", "post", {action: "geteditpreferences"}, function(){						
					});
					break;
				case("editprofilepassword"):
					this.fillData("ProfileControl.php", "post", {action: "geteditpassword"}, function(){
					});
					break;
				case("editprofilephoto"):
					this.fillData("res/"+ language +"/template/profile/upload_pic.tpl");
					break;
				case("editibuddyphoto"):
					this.fillData("res/"+ language +"/template/profile/upload_pic2.tpl");
					break;
				case("displayuploaderror"):
					this.fillData("res/"+ language +"/template/profile/upload_error.tpl");
					break;
				case("getsendmessagewindow"):
					this.fillData("res/"+ language +"/template/message/send_message.tpl", null, null, function(){
						hMessage.window.fillWindow();
					});
					break;
				case("getmessagebyid"):
					this.fillData("MessageControl.php", "post", {
						action: "getmessagebyid",
						id: hMessage.reply
						}, function(){
							
						});
					break;
				case("confirmdelete"):
					this.fillData("res/"+ language +"/template/message/confirm_delete.tpl");
					break;
				case("confirmdelete0"):
					this.fillData("res/"+ language +"/template/sequence/confirm_delete.tpl");
					break;
				case("needupdate"):
					this.fillData("res/"+ language +"/template/sequence/needupdate.tpl");
					break;
				case("nodelete"):
					this.fillData("res/"+ language +"/template/sequence/nodelete.tpl");
					break;
			}
		},
		
		hide : function(){
			this.blocker.setStyle("height", 0).setStyle("width", 0).setStyle("display", "none");
			var FxFadeOut = new Fx.Transition(Fx.Transitions.Back.easeIn);
			var StyleFadeOut = new Fx.Styles(this.div, {
				duration: 400,
				transition: FxFadeOut,
				onComplete: function(){
					hMsg.div.setStyle("display", "none");
					utility.showFlash();
					//$("root").setStyle("overflow", "auto");
					hMsg.showing = false;
				}
			});
			StyleFadeOut.start({
				top : window.getSize().size.y + this.getDivSize().height
			});
		},
		
		show : function(){
			
			utility.hideFlash();
			//hInput.initButton();
			
			/*if (!window.webkit420){
				var oldy = $("root").getSize().scroll.y;
				$("root").setStyle("overflow", "hidden");
				$("root").scrollTop = oldy;
			}*/
			
			var instance = this;
			instance.blocker.setStyle("display", "block").setOpacity(0.3).setStyle("width", window.getScrollWidth()).setStyle("height", window.getScrollHeight());
			
			var FxBounceIn = new Fx.Transition(Fx.Transitions.Bounce.easeOut, 2);
			var StyleBounceIn = new Fx.Styles(this.div, {
				duration: 600,
				transition: FxBounceIn,
				onComplete: function(){
					
					//if ($defined("msg_close_btn")) $("msg_close_btn").addEvent("click", hide);
					hMsg.showing = true;
					hInput.initInputField();
					(function(){hInput.initButton()}).delay(200);
					
					if ($defined($$("input[tag=default_focus]")[0])){
						$$("input[tag=default_focus]")[0].focus();
						$$("input[tag=default_focus]")[0].addEvent("keydown", function(e){
							var evt = new Event(e);
							if (evt.key == "space" || evt.key == "enter"){
								hMsg.hide();
							}
							evt.preventDefault();
							evt.stopPropagation();
						});
					}
					
					if ($defined($$("textarea[tag=default_focus]")[0])) $$("textarea[tag=default_focus]")[0].focus();
					
					if (window.ie7){
						instance.blocker.removeEvents();
						instance.blocker.addEvent("click", function(){
							// nudge the windows
							var FxNudge = new Fx.Styles(instance.focuser, {
								duration : 500,
								fps: 50,
								wait : true,
								onComplete : function(){
									instance.focuser.setStyle("opacity", 0);
								}
							});
							
							FxNudge.start({
								opacity : [0, 1],
								top : [0, instance.getCenterOffset().y + 15],
								left : [0, instance.getCenterOffset().x + 15],
								width : [window.getWidth(), instance.getDivSize().width - 30],
								height : [window.getHeight(), instance.getDivSize().height - 20]
							});
						});
					}
				}
			});
			this.div.setStyle("top", this.getDivSize().height*-1).setStyle("display", "block").setStyle("left", this.getCenterOffset().x);
			StyleBounceIn.start(
				{
					top : this.getCenterOffset().y
				}
			)
		},
		
		/* private functions */
		getDivSize : function(){
			return {
				width : this.div.getSize().scrollSize.x,
				height : this.div.getSize().scrollSize.y
			}
		},
		
		getCenterOffset : function(){
			if (window.ie7 || window.gecko || window.webkit420){
				return {
					x : screenCenter.x() - this.getDivSize().width/2,
					y : screenCenter.y() - this.getDivSize().height/2
				}
			} else return {
				x : screenCenter.x() - this.getDivSize().width/2 + window.getScrollLeft(),
				y : screenCenter.y() - this.getDivSize().height/2 + window.getScrollTop()
			}
		}
	}
	
	hInput.initButton();
	hInput.initInputField();
	hMsg.center();
	hMenu.initButton();
	
	//if ($defined($("btn_home"))) $("btn_home").fireEvent("mouseenter").fireEvent("click");
	hMember.next();
	(function(){hMember.next()}).periodical(7000);
	
	
	
});
