function showHide(update, icon) {
 if (document.getElementById(icon).title != "Hide Details") {
   document.getElementById(icon).title = "Hide Details";
   document.getElementById(icon).height = "21";
   document.getElementById(icon).width = "21";
   document.getElementById(icon).src = "/images/down-arrow.gif";
 } else {
   document.getElementById(icon).title = "Show Details";
   document.getElementById(icon).height = "20";
   document.getElementById(icon).width = "21";
   document.getElementById(icon).src = "/images/right_arrow.gif";
 }
 if (update.style.display == "none") {
   update.style.display = "";
 }
 else {
   update.style.display = "none";
 }
}

function showHide2(update, icon) {
 if (document.getElementById(icon).title != "Hide Details") {
   document.getElementById(icon).title = "Hide Details";
   document.getElementById(icon).height = "21";
   document.getElementById(icon).width = "21";
   document.getElementById(icon).src = "/images/down-arrow2.gif";
 } else {
   document.getElementById(icon).title = "Show Details";
   document.getElementById(icon).height = "20";
   document.getElementById(icon).width = "21";
   document.getElementById(icon).src = "/images/right_arrow2.gif";
 }
 if (update.style.display == "none") {
   update.style.display = "";
 }
 else {
   update.style.display = "none";
 }
}

function selectAddendaSet(id) {
  var obj = document.getElementById(id);
  var indv = id.substring(7);
  var el, i=1;
  while(el=document.getElementById(indv + i))  {
    el.checked = false;
    el.disabled = obj.checked;
    selectAddendaSubSet(indv + i);
    i++;
  }
}

function selectAddendaSubSet(id) {
  var obj = document.getElementById(id);
  var el, i=1;
  while(el=document.getElementById(id + i))  {
    /*var xel = document.getElementById('x' + id + i);
    xel.checked = obj.checked;*/

    el.checked = obj.checked;
    el.disabled = obj.disabled;
    //el.disabled = obj.disabled || obj.checked;
    /*if (obj.checked) {
      el.checked = true;
      el.disabled = false;
      el.style.visibility = "hidden";
    } else if (obj.disabled) {
      el.checked = false;
      el.disabled = true;
      el.style.visibility = "hidden";
    } else {
      el.checked = false;
      el.disabled = false;
      el.style.visibility = "visible";
    }*/
    i++;
  }
}

function deselectAddendaSet(obj, grpId) {
  var grpObj = document.getElementById(grpId.id);
  if(!obj.checked) {
    grpObj.checked = false;
  }
}

function selectSubSet(bu) {
  var bb = bu.id;
  var indv = bb.substring(7);
  var el, i=1;
  while(el=document.getElementById('individual' + (indv) + (i++)))  {
    el.checked = false;
    el.disabled = bu.checked;
  }
}

function selectBoughtSubSet(bu) {
  var bb = bu.id;
  var indv = bb.substring(7);
  var el, i=1;
  while(el=document.getElementById('boughtindv' + (indv) + (i++)))  {
    el.checked = false;
    el.disabled = bu.checked;
  }
}

function addItemsToCartForDigital(form,docType){
  for(var i=0;i<form.length;i++) {
    if(form.elements[i].id.substring(0,10)=='individual') {
      if(form.elements[i].checked) {
        if (docType=='plan') {
          document.getElementById("error").innerHTML = 'ERROR: Digital plans can only be purchased in sets';
        } else if (docType=='addenda') {
          document.getElementById("error").innerHTML = 'ERROR: Digital addenda can only be purchased as complete bundle';
        } else {
          document.getElementById("error").innerHTML = 'ERROR: Digital documents can only be purchased in sets';
        }
        document.getElementById("error").style.display = "";
        return false;
      }
    }
  }

  for( i=0;i<form.length;i++ ) {
    if(form.elements[i].id.substring(0,7)=='abundle') {
      if(form.elements[i].checked) {
        return isIndividualCopyChecked(form, docType);
      }
    }
  }

  if(docType=='spec') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Specifications to purchase';
  } else if (docType=='plan') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Plans to purchase';
  } else if (docType=='addenda') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Addenda to purchase';
  } else {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any documents to purchase';
  }
  document.getElementById("error").style.display = "";
  return false;
}

function isIndividualCopyChecked(form,docType) {
  for(var i=0;i<form.length;i++) {
    if(form.elements[i].id.substring(0,10)=='individual') {
      if(form.elements[i].checked) {
        if (docType=='plan') {
          document.getElementById("error").innerHTML = 'ERROR: Digital plans can only be purchased in sets';
        } else if (docType=='addenda') {
          document.getElementById("error").innerHTML = 'ERROR: Digital addenda can only be purchased as complete bundle';
        } else {
          document.getElementById("error").innerHTML = 'ERROR: Digital documents can only be purchased in sets';
        }
        document.getElementById("error").style.display = "";
        return false;
      }
    }
  }
  return true;
}

function addSubItemsToCart(form,docType){
  if(!isAnyItemsChecked(form,docType)) {
    return false;
  } else {
    //Add code to disable digitalSubmit more then once.
    var button = document.getElementById("digitalSubmit");
    if( button.disabled ) return false;
    button.disabled=true;
    form.action="/addmultitocart.htm";
    //below target added by sudhakar
    form.target="";
    form.submit();
  }
  return true;
}

function isAnyItemsChecked(form,docType){
  for(var i=0;i<form.length;i++) {
    if(form.elements[i].type=='checkbox' && form.elements[i].checked) {
      return true;
    }
  }
  if(docType=='spec') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Specifications to purchase';
  } else if (docType=='plan') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Plans to purchase';
  } else if (docType=='addenda') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Addenda to purchase';
  } else {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any documents to purchase';
  }
  document.getElementById("error").style.display = "";
  return false;
}
//end project overview

/*
  downloadFiles
  Subproducts page. Opens popup window and posts form to it.
  @param df form object
  @param docType string used for isAnyItemsCheckedForDownloads()
  @returns bool
 */
function downloadFiles(f, docType){
  if( ! isAnyItemsCheckedForDownloads(f,docType) ) return false;
  openDownloadPopup(f);
  return true;
}

/*
  downloadOrder
  Purchase history page.
  @param f form object
  @returns bool
 */
function downloadOrder(f) {
  openDownloadPopup(f);
  return true;
}

/*
  openDownloadPopup
  Private function used by downloadFiles and downloadOrder.
  @param f form object
 */
function openDownloadPopup(f) {
  window.name="MGHDownloadOpener";
  window.open("","downloadWindow","status=0,toolbar=0,location=0,menubar=0,directories=0,scrollbars=yes,resizable=1,width=440,height=160");
  f.action = "/batchdownload.htm";
  f.target = "downloadWindow";
  f.submit();
}

function isAnyItemsCheckedForDownloads(df,docType){
  for(var i=0;i<df.length;i++) {
    if(df.elements[i].type=='checkbox' && df.elements[i].checked) {
      return true;
    }
  }
  if(docType=='spec') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Specifications to Download';
  } else if (docType=='plan') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Plans to Download';
  } else if (docType=='addenda') {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any Addenda to Download';
  } else {
   document.getElementById("error").innerHTML = 'ERROR: You have not selected any documents to Download';
  }
  document.getElementById("error").style.display = "";
  return false;
}

function printPageContent(windowId, containerDivId, cdn) {
  try{
    var window = document.getElementById(windowId);
    var oContent = document.getElementById(containerDivId).innerHTML;
    var oDoc = (window.contentWindow || window.contentDocument);
    if (oDoc.document) oDoc = oDoc.document;
    oDoc.write("<head>");
    oDoc.write('<link rel="stylesheet"" href="' + cdn + '/css/mgh_common.css" type="text/css" media="all"/>');
    oDoc.write('<link rel="stylesheet" href="' + cdn + '/css/mgh_print.css" type="text/css" media="print"/>');
    oDoc.write('<!--[if IE 6]><link rel="stylesheet" href="' + cdn + '/css/mgh_ie6.css" type="text/css"/><![endif]-->');
    oDoc.write('<!--[if !IE 6]><link rel="stylesheet" href="' + cdn + '/css/mgh_ie.css" type="text/css" media="all" /><![endif]-->');
    oDoc.write("<title>Print Purchase Confirmation</title>");
    oDoc.write("</head><body onload='this.focus();this.print()'>");
    oDoc.write('<div id="printBox">' + oContent + "</div></body>");
    oDoc.close();
  }
  catch(e){
    self.print();
  }
}

/*
  showHideAddendaUpdates
  Product detail and report tab pages.
  @param a anchor object to change innerHTML
  @returns void
 */
function showHideAddendaUpdates(a) {
  updatesBox= document.getElementById("addendaupdates");
  if( updatesBox.style.display == "block" ) {
    // HIDE
    a.innerHTML= "See Project Update History";
    updatesBox.style.display= "none";
  } else {
    // SHOW
    a.innerHTML= "Hide Project Update History";
    updatesBox.style.display= "block";
  }
}

/*
  submitFormOnce
  ProductDetail and subproducts pages. Prevents more than once click to the submit button
  from posting the form more than once.
    NOTE: In some browsers, this will not allow user to post when they come back
    using the back button and click again.
  @param f form object
  @returns true first time, false after that
 */
function submitFormOnce(f) {
  if( ! f.id ) { alert("There is no id on this form.");return false; }
  if( typeof f._isSubmitted == "undefined" ) {
    f._isSubmitted = true;
    addToCartAsync(f, "/addtocart.htm");
  }
  return false;
}

/*
  addToProductRegistry
  Subproducts page. Called from addProductsToCart. Creates an array of hard copy and digital
  copy subproduct productIds. Returns true if copyType+productId is already registered,
  false if not yet registered. The funny join is used because IE doesn't support Array.indexOf.
  @param f form object
  @param element form object element (checkbox)
  @param copyType (DC|HC) digital or hard copy.
  @returns (false|true) whether element's value is already registered.
 */
function addToProductRegistry(f, index, copyType) {
  if( typeof f.productRegistry == "undefined" ) f.productRegistry= new Array();
  if( typeof f.productRegistry[copyType] == "undefined" ) f.productRegistry[copyType]= new Array();
  if( ("|"+f.productRegistry[copyType].join("|") + "|").indexOf(index) == -1 ) {
    f.productRegistry[copyType].push(index);
    return false;
  } else {
    return true;
  }
}

/*
  addProductsToCart
  @requires jquery
  Subproducts page. Loops through all subproduct checkboxes to make sure a subproduct
  can only be added once to the cart even if you double click, click more than once
  before the cart page loads or if you hit the back button without refreshing.
    NOTE: submitFormOnce() should be used except for subproducts where a user may want
    to add to cart, click back, and add different products. submitFormOnce() doesn't
    allow this.
  @param f form object.
  @param docType (spec|plan|addenda) Used exlusively for isAnyItemsChecked.
  @param copyType (DC|HC) digital or hard copy.
  @returns (true|false)
 */
function addProductsToCart(f, docType, copyType) {
  if( typeof f == "string" ) f= document.getElementById(f);
  var count = 0;
  if( ( docType == 'addenda' || docType == 'plan' ) && copyType == 'DC' && ! addItemsToCartForDigital(f, docType) )
    return false;
  if( typeof addProductsToCartIsRunning != "undefined" && addProductsToCartIsRunning ) {
    return false;
  }
  addProductsToCartIsRunning= true;
  var isOkToSubmit= false;
  if( ! isAnyItemsChecked(f,docType) ) return false;

  // Some masters have 8,000 subproducts which could crash some browsers
  // Limit to ~500 subproducts, which is a little over 1000.
  if( f.elements.length < 1000 ) {
    // loop through checkboxes, add to registry so only submitted once.
    for( e=0; e < f.elements.length; e++ ) {
      element= f.elements[e];
      if( element.type != 'checkbox' ) continue;
      matches= element.name.match(/product\[(\d+)\]\.quantity/);
      if( matches != null ) {
        elementIndex= matches[1];
        if( element.checked ) {
          // Add to reg. If true, it is already in there, uncheck it.
          if( addToProductRegistry(f, elementIndex, copyType) ) {
            element.checked= false;
          } else {
            isOkToSubmit= true;
          }
        }
      }
    }
  } else {
    // Skipping since there are too many products to quickly loop through.
    // This removes the ability to go back to add a different set w/o reloading.
    isOkToSubmit= f.copyType.value == '';
  }

  for (var i=0; i < f.length; i++) {
    if (f.elements[i].name != 'addendaGroup' && f.elements[i].type == 'checkbox' && f.elements[i].checked) { // DO NOT include addenda group, since it is not a product
      count++;
    }
  }

  if( ! isOkToSubmit ) {
    alert("Please click the buy or order button once. If you are having difficulty adding these items to your cart, try reloading the page.");
    addProductsToCartIsRunning= false;
    return false;
  }

  if(count > 200) {
    var msg = "There are total number of " + count + " products you are trying to add to the shopping cart, which could take a minute or more to complete this process. Would you like to continue?";
    if (!confirm(msg)) {
      addProductsToCartIsRunning= false;
      return false;
    }
  }
  addProductsToCartIsRunning= false;
  document.addProductsAJAXIsCancelled= false;
  f.copyType.value=copyType;
  addToCartAsync(f, "/addmultitocart.htm");
  return false;
}

/*
  addToCartAsync
  @requires jquery
  Product detail and subproducts pages. Takes all fields from a form and submits them through an AJAX call.
  Shows a progress indicator.
  @param formId string id of the form to submit
  @param url string url of the form action to use.
*/
function addToCartAsync(form, url) {
  if( ! $("#"+form.id) ) { alert("Form does not exist."); return false; }
  showProgressIndicator();
  // MD: AJAX- This logic does not help to pass the request objects for webtrends
  /*$.ajax({
          type: "POST",
          url: url,
          data: $("#" + formId).serialize(),
          success: function (msg) {
            addToCartAsyncOnComplete(msg);
          }
        });*/
    form.action=url;
    form.method="POST";
    form.target="";
    form.submit();
}
/*
  addProductsToCartOnComplete
  @requires jquery
  Product Detail and Subproducts pages. Called by addToCartAsync() via jquery.ajax.
  @param msg
  @returns
 */
function addToCartAsyncOnComplete(msg) {
  //if( typeof document.addProductsAJAXIsCancelled != "undefined" && document.addProductsAJAXIsCancelled ) return;
  if( msg.indexOf("success") > -1 ) {
    window.location="/viewcart.htm";
  } else {
    hideProgressIndicator();
    alert("There was a problem adding these items to your cart.\n\n" + msg);
  }
}

/*
  cancelAddProductsToCart
  @requires jquery
  Subproducts page. Prevents page from forwarding to cart and hides message overlay.
 */
function cancelAddToCartAsync() {
  /*
  cancelMessage= "If you cancel, some products may already be in your cart. Please review the products in your cart. Are you sure you want to cancel?";
  if( ! confirm(cancelMessage) ) return;
  */
  document.addProductsAJAXIsCancelled= true;
  hideProgressIndicator();
}

/*
  warnAboutTab
  Subproducts page. Used to warn customers when the page will take too long to load.
  @param tabName = [specs|plans|addenda]
  @param count = int number of subproducts
  @returns (true|false)
 */
function warnAboutTab(tabName, count) {
  var formattedCount= "";
  var countString= count.toString();
  for( var i=0; i < countString.length; i++ ) {
    if( i && i%3 == 0 ) formattedCount = "," + formattedCount;
    formattedCount = countString.substr(countString.length - i - 1, 1) + formattedCount;
  }
  var msg= "There are " + formattedCount + " " + tabName + " for this project, which could take a minute or more to display. Would you like to continue?";
  return confirm(msg);
}

function showProgressIndicator() {
  document.addProductsTimer= setTimeout( startProgressIndicator, 100 );
}

function startProgressIndicator() {
  if( $("#overlayContainer") ) $("#overlayContainer").fadeIn(200);
}

function hideProgressIndicator() {
  if( typeof document.addProductsTimer != "undefined" ) clearTimeout(document.addProductsTimer);
  if( $("#overlayContainer") ) $("#overlayContainer").fadeOut(200);
}
