var closeTimer = null;
var menuItem = null;

function setSearchBoxValue(textbox)
{
    if (textbox.getAttribute('value') == 'Enter search 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)');
    }
}

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;
	}
}

$(document).ready(function() {
    var cls = 'ie';
    if($.browser.mozilla)
        cls = 'ff';
    if($.browser.safari)
        cls = 'sf';
    $('html').addClass(cls);
});

function advSearchSubmit()
{
    if ($.browser.msie)
    {
        // To rectify HKSCS searching on machines with HKSCS.
        var doc = document.getElementById('RIGHT').contentWindow.document;
        var f = doc._DominoForm;
        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);
                }
            }			    
        }
    }
    return true;
};

function quickSearchSubmit()
{
    var f = document._DominoForm;
    var ele = f.elements["SearchTerm_UserInput"];

    setSearchBoxValue(ele);

    var input = ele.value;
    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;
    }
    else
        f.elements["SearchTerm"].value = input;
    return true;
};

function iframeOnLoad()
{
    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 {
        if (fwin.location.href.toLowerCase().indexOf("legislation.gov.hk") < 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.

    fwin.document.onkeydown=iframePaging;    // to allow page up/down... keys.
    
    var cls = 'ie';
    if($.browser.mozilla)
        cls = 'ff';
    fwin.document.documentElement.setAttribute("class", cls);
    
    document.getElementById('body_main').style.height = '100px';    
	fr.height = 150;
    
    //find the width of the internal page
    var the_width=fwin.document.body.scrollWidth;
    //change the width of the iframe
    $('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
    fr.height=the_height + 100;


	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 + 100));

	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);
 
    if (fwin.location.href.indexOf("/$WebSrch") > 0)
        fwin.document._DominoForm.onsubmit = advSearchSubmit;
}

function iframeResize()
{
    var frame_body = document.getElementById('RIGHT');
    var frame_win = frame_body.contentWindow;

    try {
        if (frame_win.location.href.toLowerCase().indexOf("legislation.gov.hk") < 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)
{
    var fm, laws, lang, ver, vwName, params;
    
    fm = document.navForm;
    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 (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");
    }
    
    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;
}

var isLoaded = false;        
function loadPage(lang) {
    var fr=document.getElementById("RIGHT").contentWindow;
    var badHref;
    try {
        badHref = (fr.location.href.indexOf("legislation.gov.hk") < 0);
    } catch (ex) {
        return;		// avoid errors with linked GLD contents.
    }
    if (badHref && !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);
            var searchTerm = unescape(qs.substring("SearchTerm=".length + 1));
            document._DominoForm.elements['SearchTerm_UserInput'].value = searchTerm;
            if (quickSearchSubmit())
                document._DominoForm.submit();
        }
        else
        {
            fr.open("../blis_ind.nsf/WebView?OpenAgent&vwpg=CurAll" + lang + "Doc*1", "RIGHT");
        }
    }
}

function trim(s) {
    return s.replace(/^\s*/, "").replace(/\s*$/, "");
}

function getCookie(w, check_name ) {
	// first we'll split this cookie up into name/value pairs
	// note: document.cookie only returns name=value, not the other components
	var a_all_cookies = w.document.cookie.split( ';' );
	var a_temp_cookie = '';
	var cookie_name = '';
	var cookie_value = '';
	var b_cookie_found = false; // set boolean t/f default f

	for ( i = 0; i < a_all_cookies.length; i++ )
	{
		// now we'll split apart each name=value pair
		a_temp_cookie = a_all_cookies[i].split( '=' );


		// and trim left/right whitespace while we're at it
		cookie_name = a_temp_cookie[0].replace(/^\s+|\s+$/g, '');

		// if the extracted name matches passed check_name
		if ( cookie_name == check_name )
		{
			b_cookie_found = true;
			// we need to handle case where cookie has no value but exists (no = sign, that is):
			if ( a_temp_cookie.length > 1 )
			{
				cookie_value = unescape( a_temp_cookie[1].replace(/^\s+|\s+$/g, '') );
			}
			// note that in cases where cookie is initialized but no value, null is returned
			return cookie_value;
		}
	}
	return null;
}

function setCookie(w, name, value, expires, path, domain, secure )
{
    /*
    if the expires variable is set, make the correct
    expires time, the current script below will set
    it for x number of days, to make it for hours,
    delete * 24, for minutes, delete * 60 * 24
    */
    var expires_date;
    if ( expires )
    {
        expires = expires * 1000 * 60 * 60 * 24;
        // set time, it's in milliseconds
        var today = new Date();
        today.setTime( today.getTime() );
        expires_date = new Date( today.getTime() + (expires) );
    }

    w.document.cookie = name + "=" + value +
    ( ( expires ) ? ";expires=" + expires_date.toGMTString() : "" ) +
    ( ( path ) ? ";path=" + path : "" ) +
    ( ( domain ) ? ";domain=" + domain : "" ) +
    ( ( secure ) ? ";secure" : "" );
}

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;
}