var closeTimer = null;
var menuItem = null;
var isLoaded = false;
var isBbIframeWidth = (navigator.userAgent.match(/BlackBerry[^ ]*\/4[.]6[.]0/gi) != null);
var isBbIframeHeight = (navigator.userAgent.match(/BlackBerry[^ ]*\/(4|5)[.]/gi) != null);
var isBbCbxClickState = (navigator.userAgent.match(/BlackBerry[^ ]*\/4[.]6[.]0/gi) != null);
var isSearchAllVer = false;

function setSearchBoxValue(textbox)
{
	/*if (textbox.getAttribute('value') == 'Enter search keyword(s)' || textbox.getAttribute('value') == 'Enter keyword(s)' || textbox.getAttribute('value') == '¿é¤JÃöÁä¦rµü' || textbox.getAttribute('value') == '\u8F93\u5165\u5173\u952E\u5B57\u8BCD')
    {
        textbox.setAttribute('value', '');
    }
    else if (textbox.getAttribute('value') == '')
    {
        //textbox.setAttribute('value', 'Enter search keyword(s)');
    }*/
    if (textbox.value == 'Enter search keyword(s)' || textbox.value == 'Enter keyword(s)' || textbox.value == '¿é¤JÃöÁä¦rµü' || textbox.value == '\u8F93\u5165\u5173\u952E\u5B57\u8BCD') {
    	textbox.value = '';
    }
}

function showMenu()
{
    if (this.id)
    {
	    // Cancel close timer
	    cancelCloseTimer();

	    // Close old sub menu
	    doHideMenu();

	    // Get new sub menu and show it
	    menuItem = $(this);
	    menuItem.addClass('body-main-menu-li-over');
        var div = $('div#sub' + this.id);
        div.css('display', 'block');
        div.css('top', menuItem.parent('li').offset().top);
        var offset = 10;
        if($.browser.mozilla)
            offset = 15;
        div.css('left', menuItem.parent('li').offset().left + menuItem.width() + offset);
	}
}

function doHideMenu()
{
	if(menuItem)
	{
	    menuItem.removeClass('body-main-menu-li-over');
	    $('div#sub' + menuItem.attr('id')).css('display', 'none');
	}
}

function hideMenu()
{
	closeTimer = window.setTimeout(doHideMenu, 300);
}

function cancelCloseTimer()
{
	if(closeTimer)
	{
		window.clearTimeout(closeTimer);
		closeTimer = null;
	}
}

try {
	$(document).ready(function() {
		var cls = 'ie';
		if ($.browser.mozilla)
			cls = 'ff';
		if ($.browser.safari)
			cls = 'sf';
		$('html').addClass(cls);
	});
} catch (ex) {}



function setSortByCapOrder(form_name)
{
	//R = sortby Relevances
	//C = sortby Cap
	var p = document.forms[form_name];
	if (p == null)
		return;
	var key='SortBy';
	if( p.elements[key] == null ) {
		if(key =="")
			return;
		p.innerHTML += '<input Type=HIDDEN name="' + key  + '" id="' + key + '" />';
		p.elements[key].value = 'C';
	}
	else if (p.elements[key].value =='C')
	{
		p.elements[key].value = 'R';
	}
	else
		p.elements[key].value = 'C';
}

function prepSortByCapfield(form_name,ele)
{
	var p = document.forms[form_name];
	if (p == null)
		return;
	if (ele.type == 'text' || ele.type == 'hidden' )
	{
		setValue(form_name,ele.name,ele.value);
	}
	else if (ele.type == 'select-one')
	{
		var a = "";
		for (var i=0; i<ele.options.length; i++){
			if (ele.options[i].selected==true){
				a = ele.options[i].text;
			break
			}
		}

		setValue(form_name,ele.name,a);
	}
	
}
function advSearchSubmit()
{
    var doc = document.getElementById('RIGHT').contentWindow.document;
    var f = doc._DominoForm;

    //set the form action and default sortby value to SortByCapForm
    var form_name = 'SortByCapForm';
    var fr = document.getElementById('RIGHT');
    var fwin = fr.contentWindow;
    var fm_SortByCap = document.forms[form_name];
    //fm_SortByCap.action = fwin.document._DominoForm.action;
    setValue(form_name, "default_action", fwin.document._DominoForm.action);
    //setSortByCapOrder(form_name);

    var msie = false;
    try {
    	msie = $.browser.msie;	//BlackBerry fails with $.
    }
    catch (ex) { }
    if (msie) {
        // To rectify HKSCS searching on machines with HKSCS.
        for (var i = 0; i < f.elements.length; i++) {
            var ele = f.elements[i];
            if (ele.type == 'text')
            {
                var input = ele.value;
                var htmlEsc = "";
                var isEsc = false;
                for (var j = 0; j < input.length; j++) {
                    var chHtmlEsc = input.charAt(j);
                    var chJsEsc = escape(chHtmlEsc)
                    if (chJsEsc.charAt(0) == '%' && chJsEsc.charAt(1) == 'u')
                    {
                        chHtmlEsc = "&#" + parseInt(chJsEsc.substring(2), 16) + ";";
                        isEsc = true;
                    }
                    htmlEsc += chHtmlEsc;
                }
                if (isEsc)
                {
                    var eleName = ele.name;
                    var eleId = ele.getAttribute("id");
                    ele.setAttribute("name", eleName + "_UserInput");
                    if (eleId && eleId.length > 0)
                        ele.setAttribute("id", eleId + "_UserInput");
                    var subst = doc.createElement("input");
                    subst.setAttribute("name", eleName);
                    if (eleId && eleId.length > 0)
                        subst.setAttribute("id", eleId);
                    subst.setAttribute("type", "hidden");
                    subst.setAttribute("value", htmlEsc);
                    f.appendChild(subst);
                    ele = subst;
                }
            }
            prepSortByCapfield(form_name, ele)
        }
    }
    else {
        for (var i = 0; i < f.elements.length; i++) {
            var ele = f.elements[i];
            prepSortByCapfield(form_name, ele)
        }
    }
    return true;
};

function quickSearchSubmit()
{
    var f = document._DominoForm;
    var ele = f.elements["SearchTerm_UserInput"];

    setSearchBoxValue(ele);

    var input = ele.value;

    var form_name = 'SortByCapForm';
    var fm_SortByCap = document.forms[form_name];
    //fm_SortByCap.action = f.action;
    setValue(form_name, "default_action", f.action);

    f.elements["SearchTerm"].value = input;
    try {
    	if ($.browser.msie) {
    		// To rectify HKSCS searching on machines with HKSCS.
    		var htmlEsc = "";
    		var isEsc = false;
    		for (var j = 0; j < input.length; j++) {
    			var chHtmlEsc = input.charAt(j);
    			var chJsEsc = escape(chHtmlEsc);

    			if (chJsEsc.charAt(0) == '%' && chJsEsc.charAt(1) == 'u') {
    				chHtmlEsc = "&#" + parseInt(chJsEsc.substring(2), 16) + ";";
    				isEsc = true;
    			}
    			htmlEsc += chHtmlEsc;
    		}
    		if (isEsc)
    			f.elements["SearchTerm"].value = htmlEsc;
    		/*else
    			f.elements["SearchTerm"].value = input;*/
    	}
    } catch (ex) { }
    
    //prepSortByCapfield(form_name, f.elements["SearchTerm"]);
    for (var i = 0; i < f.elements.length; i++) {
        var ele = f.elements[i];
        prepSortByCapfield(form_name, ele)
    }

    return true;
};

function iframeOnLoad(isMobile)
{
	var iframePaging = function(e) {
        //var e=e || window.frames['RIGHT'].event;
        var e=window.frames['RIGHT'].event;
        if(e&&(e.keyCode==34||e.keyCode==33||e.keyCode==40||e.keyCode==38||e.keyCode==35||e.keyCode==36))
            parent.focus();
    };

    var fr=document.getElementById('RIGHT');
    var fwin = fr.contentWindow;

    try {
	var href = fwin.location.href.toLowerCase();
	if (href.indexOf("legislation.gov.hk") < 0 && href.indexOf("hklaw.ccgo.hksarg") < 0 && href.indexOf("203.198.189.58") < 0 && href.indexOf("192.168.135.71") < 0) {
            fr.height = 670;
            scrollTo(0,0);
            return;	// avoid errors with linked GLD contents.
        }
    } catch (ex) {
        fr.height = 670;
        scrollTo(0,0);
        return;
    }

    //fr.height = 1; //Reset iframe height.
    var bbIframeHeight;
    if (href.indexOf("webview") > 0)
    	bbIframeHeight = 5200;
    else if (href.indexOf("createdocument") > 0)
    	bbIframeHeight = 9500;
    else
    	bbIframeHeight = 520;
    if (isBbIframeHeight)
    	fr.height = bbIframeHeight;
    else
		fr.height = 380; //Reset iframe height.

    fwin.document.onkeydown=iframePaging;    // to allow page up/down... keys.

    var cls = 'ie';
    try {
    if ($.browser.mozilla)
    	cls = 'ff';
   } catch (ex) { }
   fwin.document.documentElement.setAttribute("class", cls);

   if (fwin.location.href.indexOf("/$WebSrch") > 0) {
   	fwin.document._DominoForm.onsubmit = advSearchSubmit;
   }
    
    ////document.getElementById('body_main').style.height = '100px';    
	////fr.height = 150;
    
    //find the width of the internal page
	var the_width;
	//change the width of the iframe
	if (isMobile) {
		if (!isBbIframeWidth || getMinorVer(navigator.userAgent, "4.6.0.") < 303)
		{
			if (isBbIframeWidth) {
				the_width = 383;
			}
			else if (window.innerWidth)
				the_width = window.innerWidth - 20;
			else
				the_width = document.body.clientWidth; 		//ie
			if (the_width < 320) the_width = 320;
			try {
				$('div.body-section').css('width', (the_width) + 'px');
				if ($.browser.msie) {
					var btnGroup = fwin.document.body.firstChild.firstChild;
					if (btnGroup.className == "body-title-nav-btn-group" && btnGroup.offsetWidth < the_width) btnGroup.style.width = (the_width) + 'px';
				}
			} catch (ex) { }
			fr.width = the_width;
		}
   }
    else {
    	the_width = fwin.document.body.scrollWidth;
    	$('div.body-section').css('width', (the_width + 200) + 'px');
	    fr.width=the_width;
    }

    //find the height of the internal page
    var the_height = fwin.document.body.scrollHeight;
    //change the height of the iframe
    if (!the_height) the_height = 380;
    if (isMobile)
    	the_height += 20;
    else
    	the_height += 100;
    if (isBbIframeHeight)
    	the_height = bbIframeHeight;
    else
		fr.height = the_height;


	document.getElementById('body_left').style.height = null; //Reset div height
	document.getElementById('body_main').style.height = null; //Reset div height

	var body_left_height = document.getElementById('body_left').offsetHeight;
	var body_height = Math.max(body_left_height, (the_height));

	if (!isMobile) document.getElementById('body_left').style.height = body_height+ 'px';
	document.getElementById('body_main').style.height = body_height+ 'px';

    if (fwin.location.hash.length == 0 || !anchorOnPage(fwin.document.anchors, fwin.location.hash.substring(1)))
        scrollTo(0,0);
}

function iframeResize()
{
    var frame_body = document.getElementById('RIGHT');
    var frame_win = frame_body.contentWindow;

    try {
	var href = frame_win.location.href.toLowerCase();
	if (href.indexOf("legislation.gov.hk") < 0 && href.indexOf("hklaw.ccgo.hksarg") < 0 && href.indexOf("203.198.189.58") < 0 && href.indexOf("192.168.135.71") < 0) {
            return;	// avoid errors with linked GLD contents.
        }
    } catch (ex) {
        return;
    }

    var frame_items = frame_win.document.getElementsByTagName("div");
    for (var i = 0; i < frame_items.length; i++)
    {
        if (frame_items[i].getAttributeNode("class") != null)
        {
            var divClass = frame_items[i].getAttributeNode("class").nodeValue;
            if (divClass == "body-main")
            {
                if ($.browser.mozilla)
                {
                    document.getElementById('RIGHT').style.width="790px";
                }
                else //if ($.browser.msie)
                {
                	frame_items[i].style.marginLeft = "-9px";
                    document.getElementById('RIGHT').style.width="795px";
                }
            }
            else if (divClass == "body-main-body-right")
            {
                if ($.browser.mozilla)
                	{frame_items[i].style.width = "775px";}
                else if ($.browser.safari)
                    {frame_items[i].style.width = "780px";}
                else //if ($.browser.msie)
                    {frame_items[i].style.width = "770px";}
            }
            else if (divClass == "body-main-content")
            {
                if ($.browser.mozilla)
                    {frame_items[i].style.width = "735px";}
                else if ($.browser.safari)
                    {frame_items[i].style.width = "740px";}
                else //if ($.browser.msie)
                    {frame_items[i].style.width = "770px";}
            }
        }
    }
}

function framesetResize()
{
	$(document).ready(function()
    {
		var frame_body = document.getElementById('iframe_Inpr');
		var frame_title = document.getElementById('iframe_title');
		var frame_area = document.body.clientHeight - frame_body.parentNode.parentNode.offsetTop - frame_title.offsetHeight;
		var menu_height = document.getElementById('left_menu').offsetHeight - frame_title.offsetHeight;
		frame_body.height = (frame_area < menu_height) ? menu_height : frame_area;

		body_height = Math.max(frame_area, menu_height) + frame_title.offsetHeight;		


    		if ($.browser.msie)
    		{
		document.getElementById('body_left').style.height = body_height;
		document.getElementById('body_main').style.height = body_height;
}
else
{
		document.getElementById('body_left').setAttribute('style', 'height: ' + body_height + 'px');
		document.getElementById('body_main').setAttribute('style', 'height: ' + body_height + 'px');
}
		//var frame_body.contentWindow.frames[0].document.documentElement.offsetWidth);
		window.onresize = new Function("framesetResize()"); 
	 });
}

function setBodyHeight()
{
	$(document).ready(function()
	{
		var menu_height = document.getElementById('left_menu').offsetHeight;
		var body_left_height =  document.getElementById('body_left').offsetHeight;
		var body_right_height =  document.getElementById('body_right_content').offsetHeight + document.getElementById('body_right_head').offsetHeight;
    body_left_height = 0;
		body_height = Math.max(body_left_height, Math.max(body_right_height, menu_height));
if ($.browser.msie)
{
		document.getElementById('left_menu').style.height = body_height+ 'px';
    		document.getElementById('body_left').style.height = body_height+ 'px';
    		document.getElementById('body_right').style.height = body_height+ 'px';
		document.getElementById('body_main').style.height = body_height+ 'px';
}
else
{
		document.getElementById('left_menu').setAttribute('style', 'height: ' + body_height + 'px !important');
		document.getElementById('body_left').setAttribute('style', 'height: ' + body_height + 'px !important');
		document.getElementById('body_right').setAttribute('style', 'height: ' + body_height + 'px !important');
		document.getElementById('body_main').setAttribute('style', 'height: ' + body_height + 'px !important');
 }   
    });
}

    
function navGo(nsf, chap, isMobile)
{
    var fm, laws, lang, ver, vwName, params;

    fm = document.navForm;
    if (isMobile)
    	laws = "Doc";
    else {
    	if (fm.elements["selectlaws"][0].checked)
    		laws = "Ord";
    	else if (fm.elements["selectlaws"][1].checked)
    		laws = "Sub";
    	else
    		laws = "Doc";
    }
    if (fm.elements["selectlang"].value == "Chinese")
        lang = "Chin";
    else
    	lang = "Eng";
    if (isMobile)
    	ver = "AllVer";
    else {
    	if (fm.elements["selectver"] && fm.elements["selectver"][1].checked)
    		ver = "AllVer";
    	else
    		ver = "Cur";
    }
    if (chap)
    {
        params = "*0*-";
    }
    else
    {
        params = "";
        chap = trim(fm.elements["selectchap"].value);
        if (chap.charAt(0) == 'A' || chap.charAt(0) == 'a')
        {
            var re = new RegExp("A" + parseInt(chap.substring(1)), "i");
            chap = chap.replace(re, 2000 + parseInt(chap.substring(1)));
        }
    }
    //chap = parseInt(chap);
    if (isNaN(parseInt(chap))) chap = -1;
    vwName = ver + (laws == "Doc" ? "All" : "") + lang + laws;
    
    ////var fr=document.getElementById("RIGHT").contentWindow;
    ////if (fr)
    {
        var path = (nsf.indexOf("blis_pdf.nsf") >= 0 ? "../../" : "../");
        ////fr.open(path + nsf + "/WebView?OpenAgent&cap=" + vwName + "*" + chap + params, "RIGHT");
        window.open(path + nsf + "/WebView?OpenAgent&cap=" + vwName + "*" + chap + params, "RIGHT");
    }

    return false;
}

function advSearch(lang)
{
    var ele;

    var fr=document.getElementById("RIGHT").contentWindow;
    if (!fr)
        return false;
    var viewName = getCookie(fr, "viewname");
    if (!viewName && (ele = document.getElementById('viewname')))
        viewName = ele.value;
    if (!viewName || viewName.length == 0)
        return false;
    if (viewName.indexOf("English") >= 0)
        lang = "Eng";
    else if (viewName.indexOf("Chinese") >= 0)
        lang = "Chin";
    var searchView = "$SelectSrchView" + (lang == "Chin" ? "Chin" : "");
    fr.open("../blis_ind.nsf/" + searchView + "?OpenView", "RIGHT");
    return false;
}

function loadPage(lang, isMobile) {
	var fr = document.getElementById("RIGHT").contentWindow;

	if (isMobile) {
		setCookie(fr, "blissearchallver", "0", null, null, null, null);
		return;
	}

    var iframeBlank;
    try {
    	iframeBlank = (fr.location.href.indexOf("legislation.gov.hk") < 0 && fr.location.href.indexOf("hklaw.ccgo.hksarg") < 0 && fr.location.href.indexOf("203.198.189.58") < 0 && fr.location.href.indexOf("192.168.135.71") < 0);
    } catch (ex) {
        return;		// avoid errors with linked GLD contents.
    }
    if (iframeBlank && !isLoaded)
    {
        isLoaded = true;
        var qs = window.location.search;
        if (qs && qs.length > "SearchTerm=".length + 1 && qs.substring(1, "SearchTerm=".length + 1) == "SearchTerm=")
        {
            var vwName;
            if (lang == "Chin")
                vwName = "Current\\All Chinese Documents";
            else
                vwName = "Current\\All English Documents";
            if (location.href.indexOf("translate.legislation.gov.hk") >= 0)
                setCookie(window, "viewname", vwName, null, "/gb/www.legislation.gov.hk/blis_ind.nsf/", null, null);
            else
                setCookie(window, "viewname", vwName, null, "/blis_ind.nsf/", null, null);
            /*setCookie(fr, "viewname", vwName, null, null, null, null);*/
            var searchTerm = unescape(qs.substring("SearchTerm=".length + 1));
            document._DominoForm.elements['SearchTerm_UserInput'].value = searchTerm;
            if (quickSearchSubmit())
                document._DominoForm.submit();
        }
        else
        {
        	var vwName;
        	if (!isMobile)
        	{
        		vwName = "CurAll" + lang + "Doc";
        		fr.open("../blis_ind.nsf/WebView?OpenAgent&vwpg=" + vwName + "*1", "RIGHT");
        	}
        }
	}
}

function toggleSearchAllVer(cbx) {
	var v;

	if (isBbCbxClickState) {
		isSearchAllVer = !isSearchAllVer;
		v = (isSearchAllVer ? 1 : 0);
	}
	else {
		v = (cbx.checked ? 1 : 0);
	}
	var fr = document.getElementById("RIGHT").contentWindow;
	setCookie(fr, "blissearchallver", v, null, null, null, null);
}

function trim(s) {
    return s.replace(/^\s*/, "").replace(/\s*$/, "");
}

function anchorOnPage(anchors, name)
{
    if (!anchors)
	return false;
    for (var i = 0; i < anchors.length; i++)
    {
	if (anchors[i].name == name)
	    return true;
    }
    return false;
}

function setValue(form_name, key, value ) {
	if (value == null || !key || key == "") return;
	var p = document.forms[form_name];
	if (p !=null)
	{
		if (p.elements[key] == null) {
			//if(key =="")
			//	return;
			//p.innerHTML += '<input Type=HIDDEN name="' + key  + '" id="' + key + '" value=""/>';
			var input = document.createElement("input");
			input.id = key;
			input.name = key;
			input.type = "hidden";
			input.value = value;
			p.appendChild(input);
		}
		else
			p.elements[key].value = value;
	}
}

function getMinorVer(userAgent, major) {
	var p = userAgent.indexOf(major);
	if (p < 0) return NaN;
	var s = userAgent.substring(p + major.length);
	return parseInt(s);
}
