// below here is Telerik-specific (in fact, RadPanelBar-specific)
var firstLoad = true, justThisMinuteClicked = false;

function ClientLoad(panelBar_ID, lblMessage_ID, breadCrumb_ID, hdnBreadCrumb_ID, mainContentTitle_ID, hdnSearchID_ID, hdnRegionID_ID)
{
  // check for special behaviour on the first loading of the page
  if (firstLoad)
  {
    // parse request string
    qs();
    var regionID = qsParm['RegionID'];
    var searchID = qsParm['SearchID'];
    // if values not present, check hidden fields as well: could be there due to URL rerouting
    if (regionID == undefined) regionID = document.getElementById(hdnRegionID_ID).value;
    if (searchID == undefined) searchID = document.getElementById(hdnSearchID_ID).value;
    // see if RegionID has been sent through the request string
    if (regionID != '')
    {
      // POLITICS PORTAL page only
      // find the LH tree (panel bar control)
      var panelBar = $find(panelBar_ID);
      // get first root-level item of the Politics Portal LH nav, which is "Search by country"
      var countrySearchItem = panelBar.get_items().getItem(0);
      // show that item as expanded in the LH panel
      countrySearchItem.expand();
      // now search for the item with value RegionID + 1100000 (a number set in vwSubPoliticsPortal)
      var regionItem = panelBar.findItemByValue(parseInt(regionID) + 1100000);
      // rather than just expand, simulate an actual click in order to call the client-side events associated with it
      //regionItem.expand();
      regionItem.click();
    }
    // or see if a SearchID has been sent through the request string
    else if (searchID != '')
    {
      // find the LH tree (panel bar control)
      var panelBar = $find(panelBar_ID);
      // get the entry with value SearchID
      var causesClick = true;
      var searchIDValue = parseInt(searchID);
      if (searchIDValue < 0)
      {
        // if a NEGATIVE number was specified, we just expand the item rather than simulating a click
        causesClick = false;
        searchIDValue *= -1;
      }
      var item = panelBar.findItemByValue(searchIDValue);
      if (item != null)
      {
        // first expand all parent items
        var parent = item.get_parent();
        while (parent != panelBar)
        {
          parent.expand();
          parent = parent.get_parent();
        }
        // NO LONGER NECESSARY TO SIMULATE A CLICK given the Utils.FillContent() line in psa_Content.RPBAfterItemDataBound
        // this will save a round-trip and avoid a visible overwrite for the Executive Committee page
        // (http://localhost:81/Content.aspx?ParentID=2&SearchID=1000004) among others
        item.expand();
        // call function with "false" parameter at the end to indicate that this is NOT a real, physical click
        // -- this means it will skip the post-back (or content update for plain HTML) but do everything else
        ClientItemClicked(item, lblMessage_ID, breadCrumb_ID, hdnBreadCrumb_ID, mainContentTitle_ID, divPageContent_sub_lCol_ID, divPageContent_sub_rCol_ID, hdnNumCols_ID, divMainPageContent_ID, hdnPageContent_ID, hdnPageTitle_ID, ajaxManager_ID, false);
        //        if (causesClick)
//        {
//          // simulate an actual click in order to call the client-side events associated with it
//          item.click();
//        }
//        else
//        {
//          // just expand the item (the content will come from elsewhere)
//          item.expand();
//        }
      }
    }
    // make sure we don't do this again for post-backs
    firstLoad = false;
  }
}

function ClientItemClicking(args, panelBar_ID, lblMessage_ID)
{
  // if we are closing the item we opened on the last click, set flag
  var item = args.get_item();
  var panelBar = $find(panelBar_ID);
  if (item == panelBar.get_selectedItem())
  {
    justThisMinuteClicked = true;
  }
}

function CloseSiblings(panelItem)
{
  var parent = panelItem.get_parent();
  var items = parent.get_items();
  for (var i = 0; i < items.get_count(); i++)
  {
    var item = items.getItem(i);
    if (item != panelItem && item.get_expanded())
    {
      item.collapse();
    }
  }
}

function SetBreadCrumbElement(panelItem)
{
  // initialise parent
  var parent = panelItem;
  // initialise breadcrumb text
  var breadCrumbElement = panelItem.get_text(), parent;
  var level = panelItem.get_level();
  while (level > 0)
  {
    parent = parent.get_parent();
    breadCrumbElement = parent.get_text() + " > " + breadCrumbElement;
    level = parent.get_level();
  }
  return breadCrumbElement;
}

function SetBreadCrumb(panelItem, breadCrumb_ID, hdnBreadCrumb_ID)
{
  // find server-side breadcrumb DIVs
  var breadCrumb = document.getElementById(breadCrumb_ID);
  var hdnBreadCrumb = document.getElementById(hdnBreadCrumb_ID);
  if (breadCrumb)
  {
    breadCrumb.innerHTML = hdnBreadCrumb.value + " > " + SetBreadCrumbElement(panelItem);
  }
}

function SetFormat(numCols, divPageContent_sub_lCol_ID, divPageContent_sub_rCol_ID)
{
  var divPageContent_sub_lCol = document.getElementById(divPageContent_sub_lCol_ID);
  var divPageContent_sub_rCol = document.getElementById(divPageContent_sub_rCol_ID);
  var lClass, rClass;
  if (numCols == 2)
  {
    lClass = 'normal';
    rClass = 'hidden';
  }
  else
  {
    lClass = 'pageContent_sub_lCol';
    rClass = 'pageContent_sub_rCol';
  }
  divPageContent_sub_lCol.setAttribute('class', lClass);
  divPageContent_sub_rCol.setAttribute('class', rClass);
  // for IE, set the className attribute as well (easier to just use both than find the right browser-detecting tool ...)
  divPageContent_sub_lCol.setAttribute('className', lClass);
  divPageContent_sub_rCol.setAttribute('className', rClass);
}

function ErrorMessage()
{
  return 'This site does not currently work properly on your browser.  Please contact the PSA web-master at webmaster@psa.ac.uk and give the name and version number of your browser and also the platform you are using.';
}

//function PostClickPageUpdate(item, lblMessage_ID, breadCrumb_ID, hdnBreadCrumb_ID, mainContentTitle_ID)
//{
//  // remove the log-in message, if any
//  var logInMessage = document.getElementById(lblMessage_ID);
//  if (logInMessage != null)
//  {
//    logInMessage.innerHTML = '';
//  }
//  // if we are repeatedly clicking an item, return immediately
//  if (justThisMinuteClicked)
//  {
//    justThisMinuteClicked = false;
//    return;
//  }
//  // CLOSE ANY OPEN SIBLINGS
//  CloseSiblings(item);
//  // SET BREADCRUMB
//  SetBreadCrumb(item, breadCrumb_ID, hdnBreadCrumb_ID)
//  // SET TITLE OF MAIN CONTENT PANE
//  var mainContentTitle = document.getElementById(mainContentTitle_ID);
//  var titleText = item.get_text();
//  mainContentTitle.innerHTML = titleText;
//  // also set the title of the page (as seen at the top of the browser)
//  if (titleText.length > 0)
//  {
//    var lastIndex = document.title.lastIndexOf('>');
//    if (lastIndex == -1)
//    {
//      document.title += " > " + titleText;
//    }
//    else
//    {
//      document.title = document.title.substring(0, lastIndex) + " > " + titleText;
//    }
//  }
//  // finally, set item as selected (happens automatically only when actually clicked) to make sure the colour changes
//  item.select();
//}

function FillXmlObj(pageContent)
{
  // convert string literal into an XML object (browser-dependent code)
  var xmlDoc;
  try // Internet Explorer
  {
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async = "false";
    xmlDoc.loadXML(pageContent);
  }
  catch (e)
  {
    try // Firefox, Mozilla, Opera, etc.
    {
      parser = new DOMParser();
      xmlDoc = parser.parseFromString(pageContent, "text/xml");
    }
    catch (e)
    {
      xmlDoc = null;
    }
  }
  return xmlDoc;
}

function ClientItemClicked(item, lblMessage_ID, breadCrumb_ID, hdnBreadCrumb_ID, mainContentTitle_ID, divPageContent_sub_lCol_ID, divPageContent_sub_rCol_ID, hdnNumCols_ID, divMainPageContent_ID, hdnPageContent_ID, hdnPageTitle_ID, ajaxManager_ID, actualClick)
{
  // if we are repeatedly clicking an item, return immediately
  if (justThisMinuteClicked)
  {
    justThisMinuteClicked = false;
    return;
  }
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // REMOVE LOG-IN MESSAGE, if any
  var logInMessage = document.getElementById(lblMessage_ID);
  if (logInMessage != null)
  {
    logInMessage.innerHTML = '';
  }
  // CLOSE ANY OPEN SIBLINGS
  CloseSiblings(item);
  // SET BREADCRUMB
  SetBreadCrumb(item, breadCrumb_ID, hdnBreadCrumb_ID)
  // SET TITLE OF MAIN CONTENT PANE
  var mainContentTitle = document.getElementById(mainContentTitle_ID);
  var titleText = item.get_text();
  mainContentTitle.innerHTML = titleText;
  // also set the title of the page (as seen at the top of the browser)
  if (titleText.length > 0)
  {
    var lastIndex = document.title.lastIndexOf('>');
    if (lastIndex == -1)
    {
      document.title += " > " + titleText;
    }
    else
    {
      document.title = document.title.substring(0, lastIndex) + " > " + titleText;
    }
  }
  // finally, set item as selected (happens automatically only when actually clicked) to make sure the colour changes
  item.select();
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // PROCESS URL (if any)
  var url = item.get_navigateUrl();
  // arbitrary-looking test to see if the url is real (telerik server-side controls seem to generate "#" but I don't want to rely on this ...)
  if (url && url.length > 3)
  {
    // if the URL is active, return after setting the breadcrumb (now a part of PostClickPageUpdate)
    return;
  }
  // get clicked panel's attributes
  var attributes = item.get_attributes();
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // EXTRACT XML FOR PAGE CONTENT
  var pageContent = attributes.getAttribute("PageContent");
  if (pageContent == null || pageContent == '')
  {
    // return if no content is stored for this item (assume presence of hard-coded content in the page itself)
    SetFormat(2, divPageContent_sub_lCol_ID, divPageContent_sub_rCol_ID);
    return;
  }
  var xmlDoc = FillXmlObj(pageContent);
  if (xmlDoc == null)
  {
    alert(ErrorMessage());
    return;
  }
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // SET FORMAT
  // find server-side content DIVs and apply styles as necessary
  var numCols = xmlDoc.getElementsByTagName("Format")[0].getAttribute("columns");
  if (isNaN(parseInt(numCols)))
  {
    alert(ErrorMessage());
    return;
  }
  SetFormat(numCols, divPageContent_sub_lCol_ID, divPageContent_sub_rCol_ID);
  // store number of columns in hidden field in readiness for the next post-back
  var hdnNumCols = document.getElementById(hdnNumCols_ID);
  hdnNumCols.value = numCols;
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // GET AND STORE CONTENT
  var divMainPageContent = document.getElementById(divMainPageContent_ID);
  // get controls from XML blob
  var controls = xmlDoc.getElementsByTagName("Control");
  // store XML blob and page title in hidden fields in all cases
  var hdnPageContent = document.getElementById(hdnPageContent_ID);
  var hdnPageTitle = document.getElementById(hdnPageTitle_ID);
  // first encode XML blob and page title, so that we can keep ASP.NET page validation switched on
  hdnPageContent.value = htmlEncode(pageContent, false);
  hdnPageTitle.value = htmlEncode(document.title, false);
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
  // SET PAGE CONTENT *only if* this was a real click (if not, it's been done elsewhere)
  if (actualClick == true)
  {
    // unless there is just the one literal control, we are going to post back to the server
    if (controls.length == 1 && controls[0].getAttribute("type") == "Literal")
    {
      // just the one literal control, hence no post-back; clear the existing page and over-write
      var control = controls[0];
      // grab the inner HTML (OK, XML really) as a string (browser-dependent code)
      // need to cater for IE and the others separately, as only IE has the handy ".xml" property
      var innerHtml = control.xml ? control.xml : new XMLSerializer().serializeToString(control);
      // pick the HTML between the "Control" tags and convert any lingering &amp; strings to & (need the "/.../g" to do them *all*)
      // NB: the first argument of "replace" is NOT a string but a regular expression!
      var content = innerHtml.toString().substring(innerHtml.toString().indexOf('>') + 1, innerHtml.toString().lastIndexOf('<')).replace(/&amp;/g, '&');
      divMainPageContent.innerHTML = content;
    }
    else
    {
      // clear current content (avoids jarringly visible over-write)
      divMainPageContent.innerHTML = '';
      var ajaxManager = $find(ajaxManager_ID);
      if (ajaxManager != null)
      {
        // trigger partial post-back
        ajaxManager.ajaxRequest();
      }
    }
  }
  // -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- --
}

