var selectedCBs = "";


function init() {



      //  alert("init called");
        //browser type comes in handy
        var browser = navigator.appName;
        //no next nav on lastsection
        //setTimeout("removeNextFromLast();", 500);
        //get subsections, if any, into a list
        SubsectList = getObj('SubsectionList');
        if (SubsectList) {
            arrSubsectList = SubsectList.value.split(",");
        }
        //uncheck all radios and cbs
        uncheckCheckables();
        selectedCBs = "";
        resetSearchOptions();

}

function MM_swapImgRestore() { //v3.0
  var i,x,a=document.MM_sr; for(i=0;a&&i<a.length&&(x=a[i])&&x.oSrc;i++) x.src=x.oSrc;
}
//=============================================================================

function MM_preloadImages() { //v3.0
  var d=document; if(d.images){ if(!d.MM_p) d.MM_p=new Array();
    var i,j=d.MM_p.length,a=MM_preloadImages.arguments; for(i=0; i<a.length; i++)
    if (a[i].indexOf("#")!=0){ d.MM_p[j]=new Image; d.MM_p[j++].src=a[i];}}
}
//============================================================================


function userConfirm(msg){
  if(confirm(msg))
          return true
     else
          return false
}
//===========================================================================

function go(newurl){
    location.href = newurl;
}

 // ==========================================================================
function firstCallback() {

        //if response fully loaded =========================================
    	if (callingObj.readyState == 4)
        {
            //if the response is a nice one ===============================
            if(callingObj.status == 200)   {
                // create XML object to be able to extract required fields from response
                 var xmldoc = createXMLDoc(callingObj);
                 msg = xmldoc.getElementsByTagName('msg');
                 if (msg[0].firstChild)   // if there's anything in the message element, it's an error!
                 {
                    msgText = msg[0].firstChild.nodeValue;
                    alert (msgText);
                 }
                 else {
                    //no error - proceed
                    if(sid=xmldoc.getElementsByTagName('newSeriesId'))
                    {
                        if(sid[0].firstChild)
                        {
                           seriesID=sid[0].firstChild.nodeValue;
                          // alert(seriesID);
                        }
                        else{
                            alert ('got series id tag but no value')
                        }
                    }
                    else
                    {
                        alert('xml series id tag error')  ;
                    }
                 }
             }  //end if response status OK
             else
             //show error status
             {
                alert('Server replied with error: ' + XHR.status);
             }
         }   // end if ready
}

  // ========================= AJAX BASE ==================================

function  makeXHR()  {

var XHR;
  try
    {
        // Firefox, Opera 8.0+, Safari
        XHR=new XMLHttpRequest();
    }
  catch (e)
    {
    // Internet Explorer
    try
      {
      XHR=new ActiveXObject("Msxml2.XMLHTTP");
      }
    catch (e)
      {
      try
        {
        XHR=new ActiveXObject("Microsoft.XMLHTTP");
        }
      catch (e)
        {
            alert("Couldn't create XML HTTP request object");
            return false;
        }
      }
    }
      return XHR;
}


 // ==========================================================================
function initXHR(XHR, callback) {
     // alert('cb is '+ callback)    ;
     XHR.onreadystatechange=callback;
}
 // ==========================================================================
function sendXHR (XHR, target, args) {
    if (args)
        target=target+"?"+args;
    else
        args = "";
    getObj('dbg').value = target;
    XHR.open ("post", target, true);
    XHR.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    XHR.send(args);

}
// ==========================================================================
function createXMLDoc (XHR) {
	var xmlDoc;
	if (browser=="Microsoft Internet Explorer")
	{
		xmlDoc = new ActiveXObject ("Microsoft.XMLDOM");
		xmlDoc.async = false;
		xmlDoc.loadXML(XHR.responseText);
	} else {
		xmlDoc = document.implementation.createDocument ("", "", null);
		xmlDoc = XHR.responseXML;

	}

	return xmlDoc;
}// end function createXMLDoc


// ========================= END AJAX BASE ===============================


 // ==========================================================================
function setSelected(selName, val){
 // set the selected option of a select according to val passed

//not currently used - idea was to dynamically manage position in series and
// tot episodes, but it may come in handy elsewhere

    selObj = getObj(selName) ;
    for(i=0; i < selObj.options.length; i++)  {
        if(selObj.options[i].text == val)
        {
            selObj.selectedIndex=i;
            break;
        }
    }
}
 // ==========================================================================
function vHide(objID) {
 //  alert('hiding '+ objID);
    getObj(objID).style.visibility = 'hidden';
}
  // ==========================================================================
function vShow(objID) {
   // alert('showing '+ objID);
    getObj(objID).style.visibility = 'visible';
}

 // ==========================================================================
//shorthand for document.getElementById
function getObj(objID){
    obj = document.getElementById(objID);
    if(obj)
        return obj;
    else
        return false;
}

//===========================================================================
 function dontDisplay (objName) {
  // alert (objName);
    //hide something using the display attribute
    getObj(objName).style.display = "none";
   // alert (objName.id);
 }

//===========================================================================
  function inlineDisplay (objID) {
    //show something using the display attribute
    getObj(objID).style.display = "block";
 }
//============================================================================

function test () {
    alert("Hello");

}
//===========================================================================

function showOptions(btnID){
    //receives the id of the header
   //  alert (btnID);
    //strip '_header' tag from object id passed
    SectionName = btnID.replace(/btnopen/i, "");
    SectionName = SectionName.replace(/_nav/i, "");
    inlineDisplay(SectionName) ;
    vHide(btnID);
    closeBtnID = btnID.replace(/btnopen/i, "btnclose");
    vShow(closeBtnID) ;
}
//=============================================================================

function hideOptions(btnID) {
   // alert (btnID);
    SectionName = btnID.replace(/btnclose/i, "");
    SectionName = SectionName.replace(/_nav/i, "");
    dontDisplay(SectionName) ;
    vHide(btnID);
    openBtnID = btnID.replace(/btnclose/i, "btnopen");
    vShow(openBtnID) ;
}
//=============================================================================

function showNext(btnID) {

//    alert(btnID);

    /* When we built the page, we created a list of section names in
    ** a hidden <input>.  We use this to build an array to implement the idea
    ** of a div list.  nextSibling would be OK but this is less prone to error.
    */
    //get current section id
    currDivID =  'div_'+ btnID.replace(/btnnext_/i, "");
    //retrieve list of sections
    SectList = getObj('SectionList');
    ArrayList = SectList.value.split(",");
    //find current div
    for (i = 0; i < ArrayList.length; i++){
        if(currDivID == 'div_' +ArrayList[i]){
            j = i+1;
            //check bounds
            if (j <= ArrayList.length){
                NextDivID = 'div_'+ ArrayList[j];
                inlineDisplay(NextDivID);
                btnopenid =  'btnopen' + NextDivID + '_nav';
                btncloseid =  'btnclose' + NextDivID + '_nav';
                vHide(btnopenid) ;
                vShow(btncloseid)  ;
            }
            else
            {
                alert ('Array index out of bounds');
            }
        }
    }
}  //end function showNext
//=============================================================================

function cursorPointer (obj)
{
    obj.style.cursor = 'pointer';
}

//=============================================================================
function cursorDefault (obj)
{
    obj.style.cursor = 'default';
}

//=============================================================================

function removeNextFromLast(){
    //take the next button from the last nav div - could have done this server-side
    // but what the fuck...
    if (SectList = getObj('SectionList')){
    ArrayList = SectList.value.split(",");
    //find current div
    len = ArrayList.length;
    lastNextNavDiv = "div_" + ArrayList[len-1] + "_nextnav";
    alert ('lnnd is ' +  lastNextNavDiv);
    getObj(lastNextNavDiv).innerHTML = "";
    }else{
        alert ('No section list found');
    }
}
//=============================================================================

function showSubsection(ref) {
     // we're passed the id of the calling radio button (yes, it's called cb_...)
    currentSubcatDiv = ref.replace(/cb_/i,"div_");
     //show the header
    //hide all others, obviously, Watson
     for (i = 0; i < arrSubsectList.length; i++){
        listDivID = "div_" + arrSubsectList[i];
        if ( listDivID != currentSubcatDiv){
            dontDisplay(listDivID + "_header");
            dontDisplay(listDivID);
        }
    }
        inlineDisplay (currentSubcatDiv + "_header");
        inlineDisplay (currentSubcatDiv);
}
//============================================================================


function hideAllSubsections () {

  for (i = 0; i < arrSubsectList.length; i++){
    listDivID = "div_" + arrSubsectList[i];
    dontDisplay(listDivID + "_header");
    dontDisplay(listDivID);
    }
}
//=============================================================================


function uncheckCheckables(){

    inputs = getTagsByName('input');
  //  alert (inputs.length + " input tags on this page");
    for (var i=0; i < inputs.length; i++)  {
        if ((inputs[i].type == 'radio') || (inputs[i].type == 'checkbox'))
            if(inputs[i].name.indexOf('output') ==-1){
                inputs[i].checked = false;
            }
    }
}

//=============================================================================
function getTagsByName (tagName)   {
    tagSet = document.getElementsByTagName(tagName);
    return  tagSet;
}


//==========================================================================
function statsQuerySubmit () {
    alert("SQL called");
}

function resetSearchOptions (){
   //    alert('rso called ');


    if(lq = getObj('lastquery'))
    {
   //     alert('rso called - got object' + lq.value);
        //put last checked cb IDs into an array
        var lastCheckedCBs = lq.value.split(',');
        for(i = 0 ; i < lastCheckedCBs.length ; i++){
            //check the CB
            //cbObj  = getObj(lastCheckedCBs[i]);
            if(cbObj  = getObj(lastCheckedCBs[i])){
          //  alert(lastCheckedCBs[i]);
            optsDiv = cbObj.parentNode.parentNode.parentNode.parentNode.parentNode; //ugly but couldn't DOM to it
            openbtnid = 'btnopen' + optsDiv.id + '_nav';
            closebtnid = 'btnclose' + optsDiv.id + '_nav';
            optsDiv.style.display = "block";
            vHide(openbtnid) ;
            vShow(closebtnid);
            //alert('Enclosing div is ' + optsDiv);
            cbObj.checked = true;
            selectedCBs += cbObj.id;

            }
        }

       // alert('selectedCBs at end of reset loop is '+ selectedCBs);
    }
    else
    {
     //   alert('rso called - no object' );
    }

   // alert ('selectedCBs reads '+  selectedCBs);
}




function teststuff(){

//    alert(history);

   // setCookie('one')
    var str = "markmark";
    i = str.indexOf("m",3);
    alert (i);


}


function submitQuery(){

    if(isOutputSelected() && eachSectionHasOneChecked())  {
        document.OptionsForm.submit();
    }
    else {
        alert ('Please check at least one option in each section');
    }


}


function isOutputSelected(){
   //can't submit if nothing checked for output type
    inputs = getTagsByName('input');
  //  alert (inputs.length + " input tags on this page");
    for (var i=0; i < inputs.length; i++)  {
        if (inputs[i].type == 'checkbox') {
            if(inputs[i].name.indexOf('output') > -1){
                if (inputs[i].checked){
                 //   alert ('ios returning true ');
                    return true;
                }
            }
        }
    }
    return false;
}


function eachSectionHasOneChecked(){

   //  alert('Checking selection with string '+ selectedCBs );

    //get array of sections for this topic
    SectList = getObj('SectionList');
    arrSections = SectList.value.split(",");
    readyToGo = true;

    for(i = 0 ; i < arrSections.length ; i++){

        if( arrSections[i].indexOf('output') < 0){     //output section is handled separately
         // alert (arrSections[i]);
          if(selectedCBs.indexOf(arrSections[i]) == -1){
            //nothing checked for this section
            readyToGo = false;
           // alert ('Comp failed for '+ selectedCBs + ' and '+ arrSections[i]);

          }
        }
    }
     if (readyToGo)
        return true;
     else
        return false;
/*     else {
            alert ('Please check one or more options for these sections: ' + msg);
        return false;
     }*/

}


function toggleAll(cbAll){





    allChecked = getObj(cbAll).checked;
    if (allChecked) {
        selectedCBs += cbAll;
    }else {
        selectedCBs = selectedCBs.replace(cbAll, '');
    }

    stem = cbAll.replace(/all_/i, "");
    
    inputs = getTagsByName('input');
  //  alert (inputs.length + " input tags on this page");
    for (var i=0; i < inputs.length; i++)  {
        if ((inputs[i].type == 'radio') || (inputs[i].type == 'checkbox'))
            if(inputs[i].name.indexOf(stem) >= 0){
                inputs[i].checked = allChecked;
            }
    }
}

function uncheckAll (allCB){
    //called to uncheck the 'All' option when user clicks any of the others
    getObj(allCB).checked = false;
}


function trackCBClicks (objID, statsTable){



  //  alert ('TCC called with ' + objID + ' ' + statsTable);
  //Check we have at least one CB checked for each section.
    cbObjRef = getObj(objID);

    if (cbObjRef.checked){
        selectedCBs += objID;
    }else {
        selectedCBs = selectedCBs.replace(objID, '');
    }

   //  this section could be in its own function but putting it here reduces the
   //  function list in the onclick. If dealing with Post 16, need to handle differences for
  //  Scotland
   topic = statsTable.replace('stats_data_', '');
   if (topic == 'prim_sec_post_16' ){

        switch (objID) {
          //handle the all button for region
          case 'cb_all_region ':

          break;

          //handle the all button for region
          case 'cb_all_study_level ':

          break ;
          default:

                //get direct handle on objects concerned
                cbLevelA = getObj('cb_study_level_A');
                cbLevelAS = getObj('cb_study_level_AS');
                cbLevelSH = getObj('cb_study_level_Scottish_Higher');
                cbEng = getObj('cb_region_England');
                cbNI = getObj('cb_region_Northern_Ireland');
                cbWales = getObj('cb_region_Wales');
                cbScot = getObj('cb_region_Scotland');
                cbAllRegion = getObj('cb_all_region');
                cbAllLevel = getObj('cb_all_study_level');

                //handle cb disabled status
                anyNonScotChecked = cbEng.checked | cbNI.checked | cbWales.checked | cbAllRegion.checked;
                //alert('ANSC is set '+ anyNonScotChecked);
                cbLevelA.disabled = !anyNonScotChecked;
                cbLevelAS.disabled = !anyNonScotChecked
                scotChecked  = cbAllRegion.checked | cbScot.checked;
                cbLevelSH.disabled = !scotChecked ;

                //handle cb checked status for level.  The status of these CBs depends
                //on whether the appropriate region is checked.  Eg if Scotland is unchecked
                //'Scottish Higher' is unchecked.
                cbLevelSH.checked = cbScot.checked & cbLevelSH.checked;
                cbLevelA.checked = anyNonScotChecked & cbLevelA.checked  ;   //bitwise AND with region and level
                cbLevelAS.checked = anyNonScotChecked & cbLevelAS.checked; //ditto
                
                //cbLevelAS.disabled = cbObjRef.checked;


        }//end switch


    }   // end if topic post 16

}

function submitChartRequest (requestType){
/* Submits chart request, passing chart type and sql in form post */

    getObj('chartRequestType').value = requestType
    document.chartsForm.submit();

}



