var ftimeoutid = null;
var LastFloatingDDLObj = null;
function displayCustomDropBoxList(obj){
	if(ftimeoutid != null && LastFloatingDDLObj == $(obj).select(".searchTypeDropBox")[0]){
		clearInterval(ftimeoutid);
		ftimeoutid = null;
	}
}

function showCustomDropBoxList(obj){
	var fpanel = $(obj).up().select(".floatingDropBox");
	if(LastFloatingDDLObj != $(obj)){
		$$(".floatingDropBox").invoke("hide");
	}
	LastFloatingDDLObj = $(obj);
	fpanel.each(function (o){
		o.show();
	});
}

Event.observe(window, 'load', function(e) {
    var fpanel = $$(".floatingDropBox");
    fpanel.each(function(o) {
        var h = o.getHeight();
        if (h > 200) {
            o.style.height = '200px';
        }
        var top = getY(o.previous());
        o.style.top = (top + 18) + 'px';
        o.up().observe("mouseout", function(e) {
            ftimeoutid = setTimeout(function() { $$(".floatingDropBox").invoke("hide"); }, 300);
        });
    });
    if ($('exhibitorListForm') != null) {
        ExListUpdate();
    }
    $$(".sortBy").each(function(c) {
        Event.observe(c, "click", function(f) {
            if (c.checked) {
                var d = c.readAttribute("sortBy");
                $$(".sortBy").each(function(e) {
                    e.checked = false;
                    if (e.readAttribute("sortBy") == d) { e.checked = true }
                });
                ReplaceParam("sort", d)
            } else {
                $$(".sortBy").each(function(e) { e.checked = false });
                ReplaceParam("sort", "name")
            }
        })
    });
});

function ExListUpdate(){
	$('exhibitorListForm').select('input[name]').each(function (o){
		var val = o.value;
		var node = o.up(2).select(".Node_" + val)[0];
		ExListSelectItem(o.name, node, node.readAttribute('value'));
	});
}

function ExListResetForm(){
	$('exhibitorListForm').select('input[name]').each(function (o){
		o.value = "";
		var node = o.up(2).select(".Node_")[0];
		ExListSelectItem(o.name, node, node.readAttribute('value'));
	});
}

function ExListSelectItem(val, node, value){
	var obj = $($('exhibitorListForm')[val]);
	obj.value = value;
	obj.previous().innerHTML = node.innerHTML;
	$$(".floatingDropBox").invoke("hide");
}


function ExList_MakeAppointment(companyid, companyname){
	var template = $('AppointmentDetail').innerHTML;
	
	template = template.gsub(/\$tid/, "").gsub(/\$company/, companyname);
	displayLightBox(JsLabel["js.MakeAppointment.Title.Text"], template, 530);
	var today = new Date();
	$('companyId').value = companyid;
	$('appointmentDate').value = today.getDate() + "/" + (today.getMonth() + 1) + "/" + today.getFullYear();
}

function ExList_MakeAppointmentConfirm(){
	$$('.alert_field').invoke('removeClassName', 'alert_field');
	var date = $('appointmentDate').value;
	var list = date.split("/");
	if(list.length != 3){
		show_error_msg(errorMsgs["invalid_date"],new Array("#label#"),new Array(input.readAttribute('label')),date);
		return false;
	}
	var selectDate = new Date();
    selectDate.setFullYear(parseInt(list[2]),parseInt(list[1]) - 1, parseInt(list[0]));
    if(selectDate.getFullYear() != parseInt(list[2]) || selectDate.getMonth() != parseInt(list[1]) - 1 || selectDate.getDate() != parseInt(list[0]))
    {
        show_error_msg(errorMsgs["invalid_date"],new Array("#label#"),new Array($('appointmentDate').readAttribute('label')),$('appointmentDate'));
	    return false;
    }
    
    var sHour = parseInt($('sHour').value);
    var sMin = parseInt($('sMin').value);
    var eHour = parseInt($('eHour').value);
    var eMin = parseInt($('eMin').value);
    if(isNaN(sHour) || isNaN(sMin) || isNaN(eHour) || isNaN(eMin)){
    	show_error_msg(errorMsgs["invalid_date"],new Array("#label#"),new Array($('sHour').readAttribute('label')), $('sHour'));
    	return false;
    }
    sHour = parseInt(sHour);
    sMin = parseInt(sMin);
    eHour = parseInt(eHour);
    eMin = parseInt(eMin);
    if(sHour > eHour || (sHour == eHour && sMin >= eMin)){
    	show_error_msg(errorMsgs["invalid_date"],new Array("#label#"),new Array($('sHour').readAttribute('label')), $('sHour'));
    	return false;
    }
    var psourcing = $('psourcing').checked;
    var copVenture = $('copVenture').checked;
    var agentRepresent = $('agentRepresent').checked;
    var appointOthers = $('appointOthers').checked;
    var othervalue = $('appointOthersField').value;
    if(appointOthers && othervalue.blank()){
    	show_error_msg(errorMsgs["please_enter"],new Array("#label#"),new Array($('appointOthersField').readAttribute('label')), $('appointOthersField'));
    	return false;
    }
    
    if(!psourcing && !copVenture && !agentRepresent && !appointOthers){
    	show_error_msg(errorMsgs["select_empty"],new Array("#label#"),new Array($('psourcing').readAttribute('label')), $('psourcing'));
    	return false;
    }
    
    if($('Appointmessage').value.blank()){
    	show_error_msg(errorMsgs["please_enter"],new Array("#label#"),new Array($('Appointmessage').readAttribute('label')), $('Appointmessage'));
    	return false;
    }
    
    new Ajax.Request("/service/MakeAppointment.html", {
	    method: "post",
    	parameters: {"companyid": $('companyId').value, 
    		"date": date, 
    		"sHour": sHour, "sMin": sMin,  
    		"eHour": eHour, "eMin": eMin,
    		"psourcing": psourcing, 
    		"copVenture": copVenture, 
    		"agentRepresent": agentRepresent, 
    		"appointOthers": appointOthers, 
    		"appointOthersField": othervalue, 
    		"Appointmessage": $('Appointmessage').value 
    	}, 
    	onSuccess: function (response){
    		var html = '<div width="300" style="background-color: white; text-align:center; padding-top: 50px; height: 200px; color: black;"><div class="ExhibitiorListLightBox"><center>'+JsLabel["js.MakeAppointment.SuccessfulMessage.Text"]+'<div class="OKbutton" onclick="ReloadPage();">'+JsLabel["js.MakeAppointment.Button.BackToExhiborList.Text"]+'</div></center>';
			html += "</div></div>";
			displayLightBox(JsLabel["js.MakeAppointment.Title.Text"], html, 400);
    	}
    });
}

function ExhibitorListBindPage(totalrows, size){
	ExhibitorListBindPages(2, totalrows, size);
}
function ExhibitorListBindPages(page, totalrows, size){
	var totalpage = Math.ceil(totalrows / size);
	if(totalrows > 500){
		totalpage = 5;
	}
	if(totalpage < page){
		hiddenLightBox()
		window.print();
	}else{
		displayLightBox("",'<table class="sendtesting" width="100%"><tr><td class="title"><img src="/templates/ubm/en/images/loading_100x100px.gif" width="40" />'+ Math.round((page - 1) * 100 / totalpage) +"%</td></tr></table>",350);
		
		new Ajax.Request(location.pathname+"?"+GetReplaceParam("printpage", page), {method: 'get', 
			onSuccess: function(response){
			//$$(".resultPane")[0].select("tr").last().insert({after: response.responseText});
			$$(".resultPane > tbody")[0].insert({ after: response.responseText });
				setTimeout(function(){ExhibitorListBindPages(page+1, totalrows, size)}, 1000);
			}
		});
	}
}
function GetReplaceParam(j, g, a) { var f = getQueryVariable(); if (g == null) { f.unset(j) } else { f.set(j, g) } if (a != null && a.length != null) { for (var d = 0; d < a.length; d += 2) { if (a[d + 1] == null) { f.unset(a[d]) } else { f.set(a[d], a[d + 1]) } } } var c = f.toQueryString(); if (c[0] == "&") { c = c.substring(1) } return c; }

/* update @ 2011/06/28 */
function editMyExhibitorList(isSingle, value, action, refresh) {
    var gotoLogin = false;
    if ((action == "addBatch" || action == "add") && !isLogin && EList.elist.length == 0) {
        gotoLogin = true;
    }

    var v = value;
    if (action == "addBatch" || action == "removeBatch") {
        v = "";
        $$("input[name=cbExhibitor]").each(function(o) {
            if (o.checked) {
                v += v == "" ? o.readAttribute('value') : "," + o.readAttribute('value');
            }
        });
        if (v == "") {
            alert(JsLabel["js.ExhibitorList.PleaseSelect.Exhibitor.Text"]);
            return;
        }
    }
    var param = Object.extend({ action: action, v: v, eventID: EList.eventID });
    if (refresh == undefined) refresh = false;
    new Ajax.Request("/AddToMyEList.aspx", {
        onSuccess: function(response) {
            //alert(response.responseText);
            EList = response.responseText.evalJSON();
            if (gotoLogin) {
                updateEListContent();
                LoginExhibition();
            } else
                if (refresh) { location.href = location.pathname + location.search; }
            else { updateEListContent(); }
        }, method: 'post',
        parameters: param
    });
}

function viewMyExhibitorList() {
    location.href = location.pathname + "?vmel=true";
}

function checkAll(obj, name) {
    $$('input[name=' + name + ']').each(function(o) { o.checked = $(obj).checked; });
}

function LoginExhibition(a, c) {
    if (a == null) { a = false }
    if (c == null) { c = false }
    var f = '<center><table wdith="145" border="0" class="LoginLightBoxExhibitionList" >';
    f += '<tr style="padding:0px 5px;"><td colspan="2">' + JsLabel["js.Login.Box.Save.My.ExhibitionList.Text"] + '</td></tr><tr><td>&#160;</td></tr>';
    f += '<tr><td class="username">' + JsLabel["js.Login.Box.LoginName.Text"]
   + '</td><td><input type="text" onkeypress="checkBtn2(event,13) && $(\'UserPassword_LB\').focus();"  id="UserName_LB" class="username_input"/></td></tr>';
    f += '<tr><td class="password">' + JsLabel["js.Login.Box.Password.Text"]
     + '</td><td><input type="password" onkeypress="checkBtn2(event,13) && loginCheck();" id="UserPassword_LB" class="password_input"/></td></tr>';
    f += '<tr><td></td><td class="forgotPassword"><a class="forgetpwd" href="/' + info.lang + '/forgetPassword.html">'
     + JsLabel["js.Login.Box.ForgetPassword.Text"] + "</a></td></tr>";
    f += '<tr><td class="loginError" id="LoginErrorMessage" colspan="2">&nbsp;</td></tr>';
    f += '<tr><td colspan="2"><div class="registerNow">' + JsLabel["js.Login.Box.NotYetRegistered.Text"] + "<br />";
    f += '<a href="javascript:Register()" style="color: #0472C1">' + JsLabel["js.Login.Box.RegisterNOW.Text"] + "</a></div>";
    f += '<div onclick="loginCheck()" class="loginbtn">' + JsLabel["js.Login.Box.Button.Login.Text"] + "</div></td></tr>";
    f += '<tr style="padding:0px"><td colspan="2" class="ContinueAsVistor" style="background-color: #eeeeee;height:30px;padding:10px;"><center>'
    + '<a href="javascript:hiddenLightBox()">'
    + JsLabel["js.Login.Box.Login.ContinueAsVistor.Text"] + '</a></center></td></tr>';
    f += "</table></center>";
    displayLightBox(JsLabel["js.Login.Box.Title.Text"], f, null, null, null, 0);
    $("UserName_LB").focus();
    if (a) { $("LightBoxcloseBox").style.display = "none" }
}

function loginCheck() {
    //alert(EList.elist.length)
    cusloginCheck("UserName_LB", "UserPassword_LB", 'currentPage', "LoginErrorMessage",
  function(d) {
      //      if (EList.elist.length > 0) {
      //          var f = '<center><table wdith="145" border="0" class="LoginLightBoxExhibitionList" >';
      //          f += '<tr style="padding:0px 5px;"><td colspan="2">' + JsLabel["js.ExhibitorList.Add.ExhibitorList.To.Profile"] + '</td></tr><tr><td>&#160;</td></tr>';
      //          f += '<tr><td colspan="2"><center><span onclick="loginCheck()" class="confirmbtn">' + JsLabel["js.ExhibitorList.Box.Button.Yes.Text"] + '</span>';
      //          f += '&#160;&#160;<span onclick="loginCheck()" class="confirmbtn">' + JsLabel["js.ExhibitorList.Box.Button.No.Text"] + "</span></center></td></tr>";
      //          f += "</table></center>";
      //          displayLightBox(JsLabel["js.Login.Box.Title.Text"], f, null, null, null, 0);
      //          $("UserName_LB").focus();
      //          if (a) { $("LightBoxcloseBox").style.display = "none" }
      //      } else {
      //        location.href = location.pathname + location.search;
      //      }
      if (EList.elist.length > 0) {
          location.href = location.pathname + "?" + GetReplaceParam("mck", "true");
      } else {
          location.href = location.pathname + location.search;
      }
  })
}

function updateEListContent() {
    if ($('myelCount')) {
        $('myelCount').update(EList.total);
    }
    $$('span.AddToMyExhList').each(function(o) {
        if (EList.elist.find(function(i) { return 'AddToMyExhList' + i == o.readAttribute('id'); }) != undefined) {
            $('AddToMyExhList' + o.readAttribute('value')).hide(); $('RemoveMyExhList' + o.readAttribute('value')).show();
        } else {
            $('AddToMyExhList' + o.readAttribute('value')).show(); $('RemoveMyExhList' + o.readAttribute('value')).hide();
        }
    });
}

function savePreviousCookiesToMember() {
    var param = Object.extend({ action: "savePreviousCookiesToMember", v: Object.toJSON(pcEList), eventID: EList.eventID });
    new Ajax.Request("/AddToMyEList.aspx", {
        onSuccess: function(response) {
            //alert(response.responseText);
            hiddenLightBox();
            EList = response.responseText.evalJSON();
            //updateEListContent();
            location.href = location.pathname + location.search;
        }, method: 'post',
        parameters: param
    });
}

Event.observe(window, "load", function(b) {
    updateEListContent();
    if (pcEList != null) {
        var f = '<center><table wdith="180" border="0" class="LoginAlertBoxExhibitionList" >';
        f += '<tr style="padding:0px 5px;"><td colspan="2" style="font-weight:bold">' + JsLabel["js.ExhibitorList.Add.ExhibitorList.To.Profile"] + '</td></tr><tr><td>&#160;</td></tr>';
        f += '<tr><td colspan="2"><center><div onclick="savePreviousCookiesToMember()" class="confirmbtn">' + JsLabel["js.ExhibitorList.Box.Button.Yes.Text"] + '</div>';
        f += '&#160;&#160;<div onclick="hiddenLightBox();" class="confirmbtn">' + JsLabel["js.ExhibitorList.Box.Button.No.Text"] + "</div></center></td></tr>";
        f += "</table></center>";
        displayLightBox(JsLabel["js.Showroom.Quick.Enquiry.Light.Box.Title"], f, null, null, null, 0);
    }
});
