// jquery.jsonp 2.1.4 (c)2010 Julian Aubourg | MIT License
// http://code.google.com/p/jquery-jsonp/
(function(e,b){function d(){}function t(C){c=[C]}function m(C){f.insertBefore(C,f.firstChild)}function l(E,C,D){return E&&E.apply(C.context||C,D)}function k(C){return/\?/.test(C)?"&":"?"}var n="async",s="charset",q="",A="error",r="_jqjsp",w="on",o=w+"click",p=w+A,a=w+"load",i=w+"readystatechange",z="removeChild",g="<script/>",v="success",y="timeout",x=e.browser,f=e("head")[0]||document.documentElement,u={},j=0,c,h={callback:r,url:location.href};function B(C){C=e.extend({},h,C);var Q=C.complete,E=C.dataFilter,M=C.callbackParameter,R=C.callback,G=C.cache,J=C.pageCache,I=C.charset,D=C.url,L=C.data,P=C.timeout,O,K=0,H=d;C.abort=function(){!K++&&H()};if(l(C.beforeSend,C,[C])===false||K){return C}D=D||q;L=L?((typeof L)=="string"?L:e.param(L,C.traditional)):q;D+=L?(k(D)+L):q;M&&(D+=k(D)+encodeURIComponent(M)+"=?");!G&&!J&&(D+=k(D)+"_"+(new Date()).getTime()+"=");D=D.replace(/=\?(&|$)/,"="+R+"$1");function N(S){!K++&&b(function(){H();J&&(u[D]={s:[S]});E&&(S=E.apply(C,[S]));l(C.success,C,[S,v]);l(Q,C,[C,v])},0)}function F(S){!K++&&b(function(){H();J&&S!=y&&(u[D]=S);l(C.error,C,[C,S]);l(Q,C,[C,S])},0)}J&&(O=u[D])?(O.s?N(O.s[0]):F(O)):b(function(T,S,U){if(!K){U=P>0&&b(function(){F(y)},P);H=function(){U&&clearTimeout(U);T[i]=T[o]=T[a]=T[p]=null;f[z](T);S&&f[z](S)};window[R]=t;T=e(g)[0];T.id=r+j++;if(I){T[s]=I}function V(W){(T[o]||d)();W=c;c=undefined;W?N(W[0]):F(A)}if(x.msie){T.event=o;T.htmlFor=T.id;T[i]=function(){/loaded|complete/.test(T.readyState)&&V()}}else{T[p]=T[a]=V;x.opera?((S=e(g)[0]).text="jQuery('#"+T.id+"')[0]."+p+"()"):T[n]=n}T.src=D;m(T);S&&m(S)}},0);return C}B.setup=function(C){e.extend(h,C)};e.jsonp=B})(jQuery,setTimeout);

// MLC vignette content ajax library
// -------------------------------------------
// This file depends on jquery (and jqueryui for search autocomplete).
// If jqueryui is not available, search autocomplete will not be available, however search will still function.
// Latest jquery and jqueryui can be included from vignette using the following tags
// please notify vignette team if you wish to share this, so that you can be notified of version updates.
// <link type="text/css" href="/vgn-ext-templating/mlc/css/jquery-ui/jquery-ui.custom.css" rel="stylesheet" />
// <script type="text/javascript" src="/vgn-ext-templating/mlc/scripts/jquery.min.js"></script>
// <script type="text/javascript" src="/vgn-ext-templating/mlc/scripts/jquery-ui.custom.min.js"></script>

function mlcSortChannels(a,b){
     return parseInt(a.channelorder) > parseInt(b.channelorder) ? 1 : -1;
}

function mlcSortList(a,b){
     return parseInt(a.order) > parseInt(b.order) ? 1 : -1;
}

function mlcError(location, errMsg, level, namedChannel) {
    var levelFatal = "fatal";
    var message = namedChannel + " - " + location + " - " + errMsg;

    // if not a fatal error, just write a comment to the dom
//    if (level != levelFatal) {
        jQuery(document).ready(function(){
            jQuery("html").append("<!-- mlc_ajax_error: " + message + "-->");
        });

    // otherwise redirect the user to the logout and then to the error page
 //   } else {
  //      top.location.href = "/mlc/ibm_security_logout?logoutExitPage=/500.html?logoutReason=" + message;      
   // }
	return false;
}

function mlcContext(fullPath, namedChannel) {

	var BASELINE_DEPTH = 3;
	this.channelNameArea = "";
	this.channelNameL1 = "";
	this.channelNameL2 = "";
	this.fullPathL1 = "";
	this.fullPathL2 = "";
	this.isOK = false;
    this.isPopped = false;
    this.isHome = false;
    this.fullPath = fullPath;
    this.namedChannel = namedChannel;
    this.renderOverview = false;
    this.level1SelectedUrl = "";
    this.hideLevel2 = false;
    this.secureArea = true;

    // this indicator is just to allow us to determine the search form action path
    if (this.fullPath.indexOf("I'm considering MLC") > -1) this.secureArea = false;
    // drop off the leading slash for better indicator of depth after split.
	var arrFullPath = (fullPath.substring(1, fullPath.length)).split("/");
	// Define depth as the level where the visible channels start, only allow one or two levels.
	var depth = arrFullPath.length - BASELINE_DEPTH;
	if (depth > 0) {
		// Grab the site and relevant channels. We have the 'area' channel, level1 & level2 channels.
		this.channelNameArea = arrFullPath[arrFullPath.length-depth-1];
		this.channelNameL1 = arrFullPath[arrFullPath.length-depth];
		this.channelNameL2 = (depth >= 2) ? arrFullPath[arrFullPath.length-depth+1] : "";
		// Build the path to the first and second level nav.
		for(i = 0; i <  arrFullPath.length-depth; i++){
			this.fullPathL1 += '/' + arrFullPath[i];
		}
		for(i = 0; i <  arrFullPath.length-(depth-1); i++){
			this.fullPathL2 += '/' + arrFullPath[i];
		}

		this.isOK = true;
        // The popped nav is special, depends on the navbar name.
        if (this.channelNameL1 == "Popup") this.isPopped = true;
	}
}

function mlcBuildContent(namedChannel, context) {
    mlcBuildMenu(namedChannel, context);
}

function mlcBuildMenu(namedChannel, context) {

    var html = '<div id="header" class="clearfix"> \
        <div class="inner_wrapper clearfix"> \
          <div title="MLC" id="logo">MLC</div> \
          <div id="logpanel"> \
                <span class="settings_btn" style="visibility:hidden"> <a id="view_settings_btn" class="button_icon secondary" href="#setting_btn_list"> \
                    <span class="icon settings">&nbsp;</span></a></span> \
                    <span class="logdetails"> \
                    <span id="logname" class="logname"></span> \
                    <span id="lastlog" class="lastlog"></span> </span> \
            <div class="logbtn"> \
              <ul id="topnav_links" class="topnav_links clearfix"></ul> \
            <div class="global_search clearfix"> \
                  <input type="text" id="global_search_field" name="q" class="hint_txt" value="Site search" /> \
                  <a class="input_search_btn" id="global_search_submit" href="#">&nbsp;</a> \
            </div> \
            </div> \
            <div style="display: none;"> \
              <div id="setting_btn_list" class="fancy_dropdown"> \
              </div> \
            </div> \
          </div> \
        </div> \
        <div id="nav_portal"> \
          <div id="navbox"></div> \
        </div> \
    </div>';

    var htmlPopped = '<div id="header" class="clearfix"> \
	<div class="inner_wrapper clearfix"> \
		<div title="MLC" id="logo">MLC</div> \
		<div id="logpanel"> \
			<span class="logdetails"> \
			<span id="logname" class="logname"></span> \
			<span id="lastlog" class="lastlog"></span></span></div> \
		</div> \
		<div id="nav_portal"></div> \
	</div>';

    // if we already have context, use it.
    if (context) {

        if (context.isOK) {
            // Set the right html.
            if (context.isPopped) {html = htmlPopped;}
            jQuery(document).ready(function(){
                jQuery("#header_container").html(html);
            });

            mlcBuildContentRender(context);

        }

    } else {  // need to lookup the channel path to build the context

        var jsonHref = "/vgn-webapi/services/rest/mlc/" + namedChannel + "?mode=pathbyname&callback=?";
        jQuery.jsonp({
            url: jsonHref,
            timeout: 30000,
            error: function(xOptions, textStatus) {
                return mlcError("contextjsonp", textStatus, "fatal", namedChannel);
            },
            success: function(data) {
                //alert("data = " + JSON.stringify(data));
                if(data.error) return mlcError("contextrest", data.error, "fatal", namedChannel);

                var fullPath = data.channels[0].fullPath;
                var context = new mlcContext(fullPath, namedChannel);

                if (context.isOK) {
                    // Set the right html.
                    if (context.isPopped) {html = htmlPopped;}
                    jQuery(document).ready(function(){
                        jQuery("#header_container").html(html);
                    });

                    mlcBuildContentRender(context);

                }
            }
        });
    }
}

function mlcBuildContentRender(context) {

    if (context.isPopped) {
        // Setup the logo.
        mlcBuildLogo(context);
        // Setup the user nav.
        mlcBuildUserNav(context);

        // Show the body now the header is built.
        jQuery(document).ready(function(){
            mlcRevealPage();
        });

    } else {

        // Setup the main nav
        mlcBuildLevel1Menu(context);
        // Setup the top nav.
        mlcBuildTopNav(context);
        // Setup the user nav.
        mlcBuildUserNav(context);
        // Setup the logo.
        mlcBuildLogo(context);

        // render news if container div exists
        mlcBuildNewsRender(context);
        // render tools if container div exists
        mlcBuildToolsRender(context);
        // render campaigns if container div exists
        mlcBuildCampaignRender(context);
        // render footer if container div exists
        mlcBuildFooterRender(context)

    }

}

function mlcBuildLogo(context) {

    var logoClass = "adviser";
    if (context.channelNameArea == "Personal") {
        logoClass = "client";
    } else if (context.channelNameArea == "Business") {
        logoClass = "business";
    } else if (context.channelNameArea == "Institutional") {
        logoClass = "institutional";
    }    

	jQuery(document).ready(function(){
		jQuery("#logo").addClass(logoClass);
	});
	// note, href attached in mlcBuildLevel1Menu
}

function mlcBuildLevel1Menu(context) {

	var jsonHref = "/vgn-webapi/services/rest/" + context.fullPathL1 + "?mode=subchannels&callback=?";
	jQuery.jsonp({
        url: jsonHref,
        timeout: 30000,
        error: function(xOptions, textStatus) {
            return mlcError("main nav l1", textStatus, "fatal", context.namedChannel);
        },
        success: function(data) {
            //alert("data = " + JSON.stringify(data));
            if(data.error) return mlcError("main nav l1", data.error, "fatal", context.namedChannel);

            html = '<ul id="nav" class="clearfix">';
            data.channels = jQuery(data.channels).sort(mlcSortChannels);
            var homeChannelName = data.channels[0].name;
            jQuery.each(data.channels, function(i, channel) {
                var popWin = (channel.popup == "true") ? "target=\"_blank\"" : "";
                if (channel.name == context.channelNameL1) {
                    // capture the selected L1 href
                    context.level1SelectedUrl = channel.href;

                    //Current channel at this level.
                    html += "<li class=\"current\" id=\"" + channel.id + "\"><a href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                } else {
                    html += "<li id=\"" + channel.id + "\"><a href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                }
            });
            html += "</ul>";
            jQuery(document).ready(function(){
                jQuery("#navbox").html(html);
            });

            // Build the second level. For the home channel (first item) only do this if we have a context under home.
            context.isHome = Boolean(context.channelNameL1 == homeChannelName);
            if ((!context.isHome || (context.isHome && context.channelNameL2 != "")) && !context.hideLevel2) {
                mlcBuildLevel2Menu(context);
            } else {
                jQuery(document).ready(function(){
                    mlcFixIEStyles();
                    mlcRevealPage();
                });
            }

            // Attach the home link to the logo.
            var homeChannelHref = data.channels[0].href;
            jQuery(document).ready(function(){
                jQuery('#logo').click(function() {
                    window.location.href = homeChannelHref;
                });
            });
        }
	});
}

function mlcBuildLevel2Menu(context) {

	var jsonHref = "/vgn-webapi/services/rest/" + context.fullPathL2 + "?mode=subchannels&callback=?";
	jQuery.jsonp({
        url: jsonHref,
        timeout: 30000,
        error: function(xOptions, textStatus) {
            return mlcError("main nav l2", textStatus, "fatal", context.namedChannel);
        },
        success: function(data) {
            //alert("data = " + JSON.stringify(data));
            if(data.error) return mlcError("main nav l2", data.error, "fatal", context.namedChannel);

            var html = '<div id="subnav" class="subnav_panel">';
            if(context.isHome) {
                html += '<ul class="sub_links clearfix">';
            } else {
                html += '<ul class="tab_nav clearfix">';
            }

            // sort the channels
            data.channels = jQuery(data.channels).sort(mlcSortChannels);

            // cases when we don't want the overview channel are:
            // 1. the context object has explicitly turned it off
            // 2. this is the home context
            // 3. the first 2nd level channels href matches it's parent (which means they already point to the same location)
            if (context.renderOverview && !context.isHome && data.channels.length > 0 && data.channels[0].href != context.level1SelectedUrl) {
                var overviewClass = "";
                if (!context.channelNameL2) {
                    overviewClass = " class=\"active\" ";
                }
                html += "<li " + overviewClass + ">";
                html += "<a href=\"" + context.level1SelectedUrl + "\">" + "Overview</a>";
                html += "</li>";
            }

            jQuery.each(data.channels, function(i, channel) {
                if (channel.name == context.channelNameL2) {
                    var channelName = channel.name;
                    var channelHref = channel.href;
                    var popWin = (channel.popup == "true") ? "target=\"_blank\"" : "";
                    // Different html for the backto' items.
                    if(context.isHome) {
                        if (channelName.indexOf("^") > -1) {
                            channelName = channelName.substr(channelName.indexOf("^")+1);
                            if (channelHref.indexOf("^") > -1) {
                                channelHref = channelHref.substr(channelHref.indexOf("^")+1);
                            }
                            html += "<li><a href=\"" + channelHref + "\" " + popWin + "> &lt;&nbsp;" + channelName + "</a></li>";
                        } else {
                            // special case logic for vignette pages that cannot have the 'dual' name/href approach
                            if (context.channelNameArea == "Personal") {
                                html += "<li><a href=\"/online/investor/myportfolio\"> &lt;&nbsp;Back to My portfolio</a></li>";
                            } else if (context.channelNameArea == "Business") {
                                html += "<li><a href=\"/mlc/im_with_mlc/business\"> &lt;&nbsp;Back to home</a></li>";
                            } else if (context.channelNameArea == "Institutional") {
                                html += "<li><a href=\"/mlc/im_with_mlc/institutional\"> &lt;&nbsp;Back to home</a></li>";
                            } else {
                                html += "<li><a href=\"/online/home\"> &lt;&nbsp;Back to home</a></li>";
                            }
                        }
                    } else {
                        html += "<li class=\"active\" id=\"" + channel.id + "\">";
                        html += "<a href=\"" + channelHref + "\" " + popWin + ">" + channelName + "</a>";
                        html += "</li>";
                    }
                } else if (!context.isHome) {
                    html += "<li id=\"" + channel.id + "\"><a href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                }
            });
            html += "</ul></div>";
            jQuery(document).ready(function(){
                jQuery("#nav_portal").append(html);
                // Show the arrow on the active second-level tabs
                jQuery(".tab_nav").each(	function(intIndex) {
                    if (jQuery(this).children("li").hasClass("active")) {
                        // add/position arrow indicator
                        jQuery(this).children("li.active").append("<div class='css-arrow'></div>");
                        var arrow_pos = (jQuery(this).children("li.active").width() / 2) - 5;
                        jQuery(this).children("li").children(".css-arrow").css("left", arrow_pos);
                    }
                });
                mlcFixIEStyles();
                mlcRevealPage();
            });
        }
	});
}

function mlcBuildTopNav(context) {

    var namedChannel = context.channelNameArea.toLowerCase() + ".topnav";

    var jsonHref = "/vgn-webapi/services/rest/mlc/" + namedChannel + "?mode=pathbyname&callback=?";
	jQuery.jsonp({
        url: jsonHref,
        timeout: 30000,
        error: function(xOptions, textStatus) {
            return mlcError("top nav", textStatus, "fatal", namedChannel);
        },
        success: function(data) {
            //alert("data = " + JSON.stringify(data));
            if(data.error) return mlcError("top nav", data.error, "fatal", namedChannel);

            var fullPath = data.channels[0].fullPath;
            var jsonHref = "/vgn-webapi/services/rest/" + fullPath + "?mode=subchannels&callback=?";
            jQuery.jsonp({
                url: jsonHref,
                timeout: 30000,
                error: function(xOptions, textStatus) {
                    return mlcError("top nav", textStatus, "fatal", namedChannel);
                },
                success: function(data) {
                    //alert("data = " + JSON.stringify(data));
                    if(data.error) return mlcError("top nav", data.error, "fatal", namedChannel);

                    //alert("data = " + JSON.stringify(data));
                    var html = "";
                    data.channels = jQuery(data.channels).sort(mlcSortChannels);
                    jQuery.each(data.channels, function(i, channel) {
                        var popWin = (channel.popup == "true") ? "target=\"_blank\"" : "";
                        html += "<li id=\"" + channel.id + "\"><a href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                    })
                    jQuery(document).ready(function(){
                        jQuery("#topnav_links").html(html);
                        mlcFixIEStyles();
                    });
                }
            });
        }
    });
}

function mlcBuildUserNav(context) {

	// The top channel, named channel is area.topnav
	var namedChannel = context.channelNameArea.toLowerCase() + ".usernav";
	var jsonHref = "/vgn-webapi/services/rest/mlc/" + namedChannel + "?mode=pathbyname&userinfo=true&callback=?";
	jQuery.jsonp({
        url: jsonHref,
        timeout: 30000,
        error: function(xOptions, textStatus) {
            return mlcError("user nav", textStatus, "fatal", namedChannel);
        },
        success: function(data) {
            //alert("data = " + JSON.stringify(data));
            if(data.error) return mlcError("user nav", data.error, "fatal", namedChannel);

            var fullPath = data.channels[0].fullPath;

            // setup the user details
            if (data.userinfo) {
                jQuery(document).ready(function(){
                    jQuery("#logpanel .settings_btn").css("visibility", "visible");

                    // display name may have firstname, lastname, companyname in various combinations
                    var userDisplayNameArr = new Array();
                    data.userinfo.firstname ? userDisplayNameArr.push(data.userinfo.firstname) : null;
                    data.userinfo.lastname ? userDisplayNameArr.push(data.userinfo.lastname) : null;
                    data.userinfo.companyname ? userDisplayNameArr.push(data.userinfo.companyname) : null;

                    var userDisplayName = (userDisplayNameArr.length > 0) ? userDisplayNameArr.join(" ") : "";

                    jQuery("#logname").html(userDisplayName);
                    jQuery("#lastlog").html("Last login: " + data.userinfo.lastlogin);
                });
            }

            mlcFixIEStyles();

            // This is not required for the popped windows
            if (!context.isPopped && data.userinfo) {

                jQuery(document).ready(function(){
                    jQuery("a#view_settings_btn").fancybox({
                        'type'			: 'dropdown',
                        'buttonType'		: 'icon',
                        'overlayColor'		: '#fff',
                        'overlayOpacity'	: 0,
                        'autoScale'		: false,
                        'showCloseButton'	: false,
                        'autoDimensions'	: true,
                        'changeSpeed'		: 0,
                        'padding'		: 0,
                        'speedIn'		: 0,
                        'speedOut'		: 0
                    });
                    jQuery('#setting_btn_list ul li a').live('click', function() {
                        var redirect_url = jQuery(this).attr('href');
                        window.location.href = redirect_url;
                        jQuery.fancybox.close();
                    });
                });

                var jsonHref = "/vgn-webapi/services/rest/" + fullPath + "?mode=subchannels&callback=?";
                jQuery.jsonp({
                    url: jsonHref,
                    timeout: 30000,
                    error: function(xOptions, textStatus) {
                        return mlcError("user nav", textStatus, "fatal", namedChannel);
                    },
                    success: function(data) {
                        //alert("data = " + JSON.stringify(data));
                        if(data.error) return mlcError("user nav", data.error, "fatal", namedChannel);

                        var html = "<div class=\"heading\">Settings</div><ul class=\"list\">";
                        data.channels = jQuery(data.channels).sort(mlcSortChannels);
                        jQuery.each(data.channels, function(i, channel) {
                            var popWin = (channel.popup == "true") ? "target=\"_blank\"" : "";
                            html += "<li id=\"" + channel.id + "\"><a href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                        });
                        html += "</ul>";
                        jQuery(document).ready(function(){
                            jQuery("#setting_btn_list").html(html);
                            mlcFixIEStyles();
                        });
                    }
                });
            }
        }
	});
}

function mlcBuildTools(namedChannel) {
    // not required
}

function mlcBuildToolsRender(context) {

    // all wrapped in document ready due to the existence check at the start.
    jQuery(document).ready(function() {

        // only if the container exists
        if (!jQuery("#tools_container").length) return;

        var html ='<div id="tool_box"></div>';
        jQuery("#tools_container").html(html);

        var jsonHref = "/vgn-webapi/services/rest/" + context.fullPath +
                  "?contenttype=MLC-CONTENT-LIST&checkfield=SUBTYPE&checkvalue=Tools&loadlevel=large&mode=contentitem&callback=?";

        jQuery.jsonp({
            url: jsonHref,
            timeout: 30000,
            error: function(xOptions, textStatus) {
                return mlcError("tools", textStatus);
            },
            success: function(data) {
                //alert("data = " + JSON.stringify(data));

                // if we did not get a content list we will have an error, try the site section instead.
                if (context.fullPathL2 != "" && (data.error || !data.content.length)) {
                    // Only check the section home if we have not already done so.
                    if(context.fullPathL2 != context.fullPath) {

                        var jsonHref = "/vgn-webapi/services/rest/" + context.fullPathL2 +
                          "?contenttype=MLC-CONTENT-LIST&checkfield=SUBTYPE&checkvalue=Tools&loadlevel=large&mode=contentitem&callback=?";

                        jQuery.jsonp({
                            url: jsonHref,
                            timeout: 30000,
                            error: function(xOptions, textStatus) {
                                return mlcError("tools", textStatus);
                            },
                            success: function(data) {
                                //alert("data = " + JSON.stringify(data));
                                if(data.error) return mlcError("tools", data.error);
                                mlcBuildToolsRenderData(data);
                            }
                        });
                    } else {
                        if(data.error) return mlcError("tools", data.error);
                    }

                } else {
                    if(data.error) return mlcError("tools", data.error);
                    mlcBuildToolsRenderData(data);
                }
                mlcFixIEStyles();
            }
        });
    });
}

function mlcBuildToolsRenderData(data) {

    var html = "<div class=\"accordion grouped\">";
    html += "<h2 class=\"grouped_title\">";
        html += "<span class=\"heading\">" +  data.content[0].displaytitle + "</span>";
        html += "<span class=\"acc_arrow\"></span>";
    html += "</h2>";
    html += "<div id = \"acc_container\" class=\"acc_container\">"

    data.content[0].content = jQuery(data.content[0].content).sort(mlcSortList);
    jQuery.each(data.content[0].content, function(i, content) {

        // if the displaymode was not selected on the content item, default to Closed
        var displayMode = content.displaymode ? content.displaymode : "Closed";

        if(content.url != "") {
            var accordionLinkClass = "accordion link";
            accordionLinkClass += (i==data.content[0].content.length-1) ? " last" : "";
            accordionLinkClass += (displayMode.indexOf("Highlight") != -1) ? " highlight" : "";
            accordionLinkClass = "class=\"" + accordionLinkClass + "\"";

            html += "<div " + accordionLinkClass + ">"
            html += "<a href=\"" + content.url + "\">";
            html += "<span class=\"title\">" + content.title + "</span>";
            html += "<span class=\"acc_arrow pointer\"></span>";
            html += "</a>";
            html += "</div>";            

        } else {
            var accordionClass = "accordion";
            accordionClass += (displayMode.indexOf("Open") != -1) ? " open" : " closed";
            accordionClass = "class=\"" + accordionClass + "\"";
            var h2Class = (i==data.content[0].content.length-1) ? "last" : "";
            h2Class += (displayMode.indexOf("Highlight") != -1) ? " highlight" : "";
            h2Class = (h2Class.length>0) ? "class=\"" + h2Class + "\"" : "";

            html += "<div " + accordionClass + ">";
            html += "<h2 " + h2Class + ">";
            html += "<span class=\"heading\">" + content.title + "</span>";
            html += "<span class=\"acc_arrow\">&nbsp;</span>";
            html += "</h2>";
            html += "<div class=\"acc_container acc_content\">";
            html += content.body;
            html += "</div>";
            html += "</div>";
        }
    })
    html += "</div>";
    html += "</div>";
    // Just ensure we have content in the list before rendering any html.
    if (data.content[0].content.length > 0) {
        jQuery("#tool_box").html(html);
    }
}

function mlcBuildNews(namedChannel) {
    // not required
}

function mlcBuildNewsRender(context) {

    // all wrapped in document ready due to the existence check at the start.
    jQuery(document).ready(function() {

        // only if the container exists
        if (!jQuery("#news_container").length) return;

        var jsonHref = "/vgn-webapi/services/rest/" + context.fullPath +
                  "?contenttype=MLC-CONTENT-LIST&checkfield=SUBTYPE&checkvalue=News&mode=contentitem&callback=?";

        jQuery.jsonp({
            url: jsonHref,
            timeout: 30000,
            error: function(xOptions, textStatus) {
                return mlcError("news", textStatus);
            },
            success: function(data) {
                //alert("data = " + JSON.stringify(data));
                if(data.error) return mlcError("news", data.error);

                var html = "<div class=\"accordion grouped\">";
                html += "<h2 class=\"grouped_title\"><span class=\"heading\">" +
                    data.content[0].displaytitle +"</span> <span class=\"acc_arrow\">&nbsp;</span></h2>";
                html += "<div id=\"news_newsfeeds\" class=\"acc_container\">";
                html += "</div>";
                html += "</div>";

                jQuery("#news_container").html(html);

                // For each feed..
                data.content[0].content = jQuery(data.content[0].content).sort(mlcSortList);
                jQuery.each(data.content[0].content, function(i, content) {

                    // if the displaymode was not selected on the content item, default to Closed
                    var displayMode = content.displaymode ? content.displaymode : "Closed";

                    var h2Class = (i==data.content[0].content.length-1) ? "last" : "";
                    h2Class += (displayMode.indexOf("Highlight") != -1) ? " highlight" : "";
                    h2Class = (h2Class.length>0) ? "class=\"" + h2Class + "\"" : "";

                    var accordionClass = "accordion newsfeed";
                    accordionClass += (displayMode.indexOf("Open") != -1) ? " open" : " closed";
                    accordionClass = "class=\"" + accordionClass + "\"";

                    var accContainerClass = "acc_container";
                    accContainerClass += (i==data.content[0].content.length-1) ? " last" : "";
                    accContainerClass = "class=\"" + accContainerClass + "\"";

                    html = "<div " + accordionClass + ">";
                    html += "<h2 " + h2Class + "><span class=\"heading\">" + content.title + "</span><span class=\"acc_arrow\">&nbsp;</span></h2>";
                    html += "<div " + accContainerClass + ">";
                    html += "<div class=\"slider\">";
                    var newsFeedId = content.id;
                    html += "<ul><li id=\"" + newsFeedId + "\" class=\"news\"></li></ul>";
                    html += "</div>";
                    html += "</div>";
                    html += "</div>";

                    jQuery("#news_newsfeeds").append(html);
                    mlcFixIEStyles();

                    var feedHref = content.url;
                    if (feedHref.length > 0) {
                        jQuery.jsonp({
                            url: feedHref,
                            timeout: 30000,
                            error: function(xOptions, textStatus) {
                                return mlcError("feed", textStatus);
                            },
                            success: function(data) {
                                //alert("data = " + JSON.stringify(data));
                                if(data.error) return mlcError("feed", data.error);

                                // For each item in the feed..
                                html = "";
                                count = (content.count!=null && content.count > -1) ? content.count : data.content.length;
                                jQuery.each(data.content, function(i, content) {
                                    if (i>count-1) {return false;}

                                    var shortDesc = content.shortdescription;
                                    shortDesc = (shortDesc.length > 60) ? shortDesc.substr(0,60) : shortDesc;
                                    html += "<div class=\"news_item\">";
                                    if (content.imagehref) {
                                        html += "<div class=\"adspot\"><a class=\"news_link\" href=\"" + content.href + "\"><img alt=\"\" src=\"" + content.imagehref + "\"></a></div>";
                                    }
                                    html += "<div class=\"adcopy\">";
                                    html += "<h4><a class=\"news_link\" href=\"" + content.href + "\">" + content.title + "</a></h4>";
                                    html += "<div class=\"teaser\">" + shortDesc + "...</div>";
                                    html += "</div>";
                                    html += "</div>";
                                })
                                html += "<div class=\"bottom_row\"><a href=\"" + content.contenturl + "\">View all</a></div>";
                                jQuery("#" + newsFeedId).html(html);
                                mlcFixIEStyles();
                            }
                        });
                    }
                })
            }
        });
    });
}

function mlcBuildCampaign(namedChannel) {
    // not required
}

function mlcBuildCampaignRender(context) {

    // all wrapped in document ready due to the existence check at the start.
    jQuery(document).ready(function() {

        // only if the container exists
        if (!jQuery("#campaign_container").length) return;

        var jsonHref = "/vgn-webapi/services/rest/" + context.fullPath +
                  "?contenttype=MLC-CONTENT-LIST&checkfield=SUBTYPE&checkvalue=Campaign&mode=contentitem&loadlevel=large&callback=?";

        jQuery.jsonp({
            url: jsonHref,
            timeout: 30000,
            error: function(xOptions, textStatus) {
                return mlcError("campaign", textStatus);
            },
            success: function(data) {
                //alert("data = " + JSON.stringify(data));
                if(data.error) return mlcError("campaign", data.error);

                //grab a random campaign out of the returned items
                if (data.content.length >= 0) {

                    var random = Math.floor(Math.random() * data.content[0].content.length);
                    var html = "<div class=\"content_ad clearfix\">";
                    html += data.content[0].content[random].body;
                    html += " </div>";

                    jQuery("#campaign_container").html(html);

                    mlcFixIEStyles();
                }
            }
        });
    });
}

function mlcBuildFooter() {
    // not required
}

function mlcBuildFooterRender(context) {

    // all wrapped in document ready due to the existence check at the start.
    jQuery(document).ready(function() {

        // only if the container exists
        if (!jQuery("#footer_container").length) return;

        var html ='<div id="footer"> \
            <div class="footer_inner clearfix"> \
                <ul id="fnav"> \
                </ul> \
                <p>Copyright &copy; MLC </p> \
            </div> \
            </div>';

        var htmlForm = '<form method="get" action="" id="global_search_form"></form>';

        html += htmlForm;

        if (context.isOK) {

            // No further html for a popped window - no footer except the search form.
            if (!context.isPopped) {

                jQuery("#footer_container").html(html);

                currentChannelNameArea = context.channelNameArea.toLowerCase() + ".footernav";
                var jsonHref = "/vgn-webapi/services/rest/mlc/" + currentChannelNameArea + "?mode=pathbyname&callback=?";

                jQuery.jsonp({
                    url: jsonHref,
                    timeout: 30000,
                    error: function(xOptions, textStatus) {
                        return mlcError("footer", textStatus);
                    },
                    success: function(data) {
                        //alert("data = " + JSON.stringify(data));
                        if(data.error) return mlcError("footer", data.error);

                        fullPath = data.channels[0].fullPath;
                        var jsonHref = "/vgn-webapi/services/rest/" + fullPath + "?mode=subchannels&callback=?";

                        jQuery.jsonp({
                            url: jsonHref,
                            timeout: 30000,
                            error: function(xOptions, textStatus) {
                                return mlcError("footer", textStatus);
                            },
                            success: function(data) {
                                //alert("data = " + JSON.stringify(data));
                                if(data.error) return mlcError("footer", data.error);

                                var html = "";
                                data.channels = jQuery(data.channels).sort(mlcSortChannels);
                                jQuery.each(data.channels, function(i, channel) {
                                    var popWin = (channel.popup == "true") ? "target=\"_blank\"" : "";
                                    var liLastClass = (i==data.channels.length-1) ? "class=\"last\"" : "";
                                    html += "<li id=\"" + channel.id + "\"" + liLastClass + "><a class=\"external_link\" href=\"" + channel.href + "\" " + popWin + ">" + channel.name + "</a></li>";
                                })
                                jQuery("#fnav").html(html);

                                // Setup the search form events
                                mlcSetupSearchForm(context);

                                mlcFixIEStyles();
                            }
                        });
                    }
                });
            }
        }
    });
}

function mlcSetupSearchForm(context) {

    jQuery(document).ready(function() {

        // only if the container exists
        if (!jQuery("#global_search_form").length) return;

        // handle button click
        jQuery("#global_search_submit").click(function() {
            jQuery("#global_search_form").submit();
	    });

        // handle enter key
        jQuery("#global_search_field").keypress(function(e){
            if (e.which == 13){
                jQuery("#global_search_form").submit();
            }
        });

        // setup the top search box - this will fail if jqueryui is not available.
        try {
            jQuery("#global_search_field").autocomplete({
                source: "/vgn-webapi/services/search/" + context.fullPath + "?mode=autocomplete&callback=?",
                minLength: 3,
                delay: 500,
                select: function(event, ui) {
                    event.preventDefault();
                    // set the value in the field - if we just call submit here and a selection is made with the mouse,
                    // the form submits before the field is updated, so we update and then submit here.
                    jQuery("#global_search_field").val(ui.item.value);
                    jQuery("#global_search_form").submit();
                },
				open: function(event, ui) {
					// we need to increase the z-index here as it is set on the menu element rather than controlled by class..
					jQuery(".ui-menu").css("z-index", 100);
				}
            });
        } catch (e) {}

        // update form action to have the area channel url, and search criteria added as a hashtag for the ajax search page to consume.
        jQuery("#global_search_form").submit(function(event) {
            event.preventDefault();
            var searchTerms = jQuery("#global_search_field").val();
            if (searchTerms.length && searchTerms != "Site search") {
                var action = "/mlc/" + (context.secureArea ? "im_with_mlc" : "im_considering_mlc") + "/"
                        + context.channelNameArea.toLowerCase() + "/site_tools/search#/?q=" + searchTerms;

                document.location.href = action;
            }
        });
    });
}

// render an article body in a given div
function mlcRenderArticleBody(channelPath, articleTitle, divId, append) {

   	var jsonHref = "/vgn-webapi/services/rest/" + channelPath +
	    "?checkvalue=" + articleTitle + "&mode=contentitem&loadlevel=large&callback=?";

	if (!jQuery("#" + divId).length) {return mlcError("article", "div '" + divId + "' not found.")}

	jQuery.jsonp({
        url: jsonHref,
        timeout: 30000,
        error: function(xOptions, textStatus) {
            return mlcError("article", textStatus);
        },
        success: function(data) {
            //alert("data = " + JSON.stringify(data));
            if(data.error) {return mlcError("article", data.error)}

            if (data.content.length > 0) {
                if (append) {
                    jQuery("#" + divId).append(data.content[0].body);
                } else {
                    jQuery("#" + divId).html(data.content[0].body);
                }
            }
        }
	});

}

// open a jqueryui dialog containing a given article body (requires a ).
function mlcOpenArticleDialog(channelPath, articleTitle, divId, width, height) {

    if (!width) {width=500}
    if (!height) {height=500}

    // setup the dialog - if the dialog div does not already exist, create it
    if (!jQuery("#" + divId).length) {jQuery("html").append("<div id=\"" + divId + "\"></div>")}

	    // open the dialog with a loading image..
	    jQuery("#" + divId).dialog({
		title: articleTitle,
		autoOpen: false,
		height: height,
		width: width,
		modal: true,
		resizable: false,
		draggable: false
	    }).css("overflow:hidden");

	jQuery("#" + divId).html("<img src=\"/vgn-ext-templating/mlc/images/jquery/ui-anim_basic_16x16.gif\" border=\"0\">");
	jQuery("#" + divId).dialog("open");

   	var jsonHref = "/vgn-webapi/services/rest/" + channelPath +
	    "?checkvalue=" + articleTitle + "&mode=contentitem&loadlevel=large&callback=?";

	jQuery.jsonp({
		url: jsonHref,
		timeout: 30000,
		error: function(xOptions, textStatus) {
		    return mlcError("articleDialog", textStatus);
		},
		success: function(data) {
		    //alert("data = " + JSON.stringify(data));
		    if(data.error) {return mlcError("articleDialog", data.error)}

		    if (data.content.length > 0) {
		        // populate the div with the article body
		        jQuery("#" + divId).html("<div style=\"width:" + (width-40) + "px;text-align:left\">" + data.content[0].body + "</div>");
		    }
		}
	});

}

function mlcFixIEStyles() {
/***** Progressive IE injection *****/
    if (jQuery.browser.msie && jQuery.browser.version < 9) {
	    if (jQuery('body.masterkey').length) {
			jQuery('.pieInject').pieInject(
				'button, .button, .buttn, #view_settings_btn'
			);
		} else {
			jQuery('.pieInject').pieInject(
				'#view_settings_btn, h2.grouped_title, .acc_container, .accordion h2.last'
			);
		}
	}
}

function mlcRevealPage() {
    jQuery("body > div").eq(0).css("visibility", "visible");

    // these are the exceptions to the above 'first div' rule : covers masterkey + ie6 + mlc ice
    jQuery("div#w01").css("visibility", "visible");
    jQuery("div#w0").css("visibility", "visible");

    // this is for mlp
    jQuery("div#shield").css("visibility", "visible");

}

// we need links of this class to open in a new window
jQuery(".forcenewwindow").live("click", function() {
    jQuery(this).closest("a").attr("target", "_blank");
});

// catchall - this will only have an effect if the primary nav failed to load
jQuery(window).load(function() {
    mlcRevealPage();
});

