
// ajax connector
var http = createRequestObject();

// create an HTTP XML request object for later use
function createRequestObject() {

  var ro;
  var browser = navigator.appName;

  if(browser == "Microsoft Internet Explorer"){
    ro = new ActiveXObject("Microsoft.XMLHTTP");
  } else {
    ro = new XMLHttpRequest();
  }

  return ro;

}

// read search boxes and perform the new search
function doSearch(pageUrl) {

  var js_searchIssue = document.getElementById("searchIssue");
  var js_searchCategory = document.getElementById("searchCategory");
  var js_searchAuthor = document.getElementById("searchAuthor");
  var js_searchString = document.getElementById("searchString");

  var urlString = "&recall=false";

  if (js_searchIssue.value > 0) {
    urlString = urlString + "&issueid=" + js_searchIssue.value;
  }

  if (js_searchCategory.value > 0) {
    urlString = urlString + "&categoryid=" + js_searchCategory.value;
  }

  if (js_searchAuthor.value > 0) {
    urlString = urlString + "&authorid=" + js_searchAuthor.value;
  }

  if (js_searchString.value != "") {
    urlString = urlString + "&searchwords=" + escape(js_searchString.value);
  }
  
  // switch pages
  window.location.href = pageUrl + urlString;

}

// populate the search form with values
function populateSearchFields(issue,category,author,words) {

  var js_searchIssue = document.getElementById("searchIssue");
  var js_searchCategory = document.getElementById("searchCategory");
  var js_searchAuthor = document.getElementById("searchAuthor");
  var js_searchString = document.getElementById("searchString");

  if (issue > 0) {
  
    var js_issueChildren = js_searchIssue.options;
    
    for (var i = 0; i < js_issueChildren.length; i++) {
      if (js_issueChildren[i].value == issue) {
        js_searchIssue.selectedIndex = i;
        break;
      }

    }

  }

  if (category > 0) {
  
    var js_categoryChildren = js_searchCategory.options;
    
    for (i = 0; i < js_categoryChildren.length; i++) {
      if (js_categoryChildren[i].value == category) {
        js_searchCategory.selectedIndex = i;
        break;
      }
    }

  }
  
  if (author > 0) {
  
    var js_authorChildren = js_searchAuthor.options;
    
    for (i = 0; i < js_authorChildren.length; i++) {
      if (js_authorChildren[i].value == author) {
        js_searchAuthor.selectedIndex = i;
        break;
      }
    }

  }

  if (words != "") {
    js_searchString.value = unescape(words);
  }
  
}

// toggles the display of the login form
function toggleLoginForm(on) {

  var js_loginForm = document.getElementById("loginForm");

  if (on == 1) {
    js_loginForm.style.display = "block";
  } else {
    js_loginForm.style.display = "none";
  }

}

// validates the user registration form
function validateRegistration() {

  var js_newuserUsername = document.getElementById("newuserUsername");
  var js_newuserEmail = document.getElementById("newuserEmail");
  var js_newuserPassword = document.getElementById("newuserPassword");
  var js_newuserPasswordCheck = document.getElementById("newuserPasswordCheck");

  var errors = "";
  
  if (js_newuserUsername.value == "") {
    errors = errors + "You must enter a valid user name.\r\n";
  }

  if (js_newuserEmail.value == "") {
    errors = errors + "You must enter a valid email address.\r\n";
  }

  if (js_newuserPassword.value != js_newuserPasswordCheck.value || js_newuserPassword.value == "") {
    errors = errors + "Passwords do not match; please re-check.\r\n";
  }
  
  if (errors != "") {

    // if there are errors, do nothing and display them  
    errors = "Error! Registration could not be completed for the following reason(s):\r\n\r\n" + errors;
    alert(errors);
    
  } else {

    // submit the form!  
    var js_ampRegister = document.getElementById("ampRegister");
    js_ampRegister.submit();
  
  }
  
}

// add an article to cart via Ajax
function articleToCart(id) {

  var currentDate = new Date();
  var currentTs = currentDate.getTime();

  http.open("get", "webstore.php?amp_action=do_ajax_addtocart&type=article&id=" + id + "&seed=" + currentTs.toString(), true);
  http.onreadystatechange = handleArticleToCartResponse;
  http.send(null);

}

// handle article to cart response
function handleArticleToCartResponse() {

  if (http.readyState == 4) {

    var response = http.responseText;
    var data = response.split("|");
  
    if (data[0] == "ok") {
    
      var js_articleCheckToAdd = document.getElementById("checktoadd_" + data[1]);
      var js_articleInCart = document.getElementById("incart_" + data[1]);
      
      js_articleCheckToAdd.style.display = "none";
      js_articleInCart.style.display = "block";

      // update cart string
      var js_cartString = document.getElementById("cartString");
      js_cartString.innerHTML = data[2];
    
    } else {
    
      alert("Error: Article could not be added to the database. Response: " + data[0] + "|" + data[1]);
      
    }

  }
  
}


// add an issue to cart via Ajax
function issueToCart(id) {

  var currentDate = new Date();
  var currentTs = currentDate.getTime();

  http.open("get", "webstore.php?amp_action=do_ajax_addtocart&type=issue&id=" + id + "&seed=" + currentTs.toString(), true);
  http.onreadystatechange = handleIssueToCartResponse;
  http.send(null);

}

// handle issue to cart response
function handleIssueToCartResponse() {

  if (http.readyState == 4) {

    var response = http.responseText;
    var data = response.split("|");
  
    if (data[0] == "ok") {
    
      var articleList = data[1].split(",");
      
      for (var i = 0; i < articleList.length; i++) {

        var js_articleCheckToAdd = document.getElementById("checktoadd_" + articleList[i]);
        var js_articleClickToAddMain = document.getElementById("main_clicktoadd_" + articleList[i]);
        var js_articleInCart = document.getElementById("incart_" + articleList[i]);

        // if these aren't set to objects, they are probably not on this page
        if (js_articleCheckToAdd && js_articleClickToAddMain && js_articleInCart) {

          // only display new box here if the "click to add" was currently shown              
          if (js_articleCheckToAdd.style.display != "none" && js_articleClickToAddMain.style.display != "none") {
            js_articleCheckToAdd.style.display = "none";
            js_articleInCart.style.display = "block";
          }

          js_articleClickToAddMain.style.display = "none";

        }
      
      }
      
      // update cart string
      var js_cartString = document.getElementById("cartString");
      js_cartString.innerHTML = data[2];
    
    } else {
    
      alert("Error: Issue could not be added to the database. Response: " + data[0] + "|" + data[1]);
      
    }

  }
  
}

// submit the express checkout form
function doExpressForm() {

  if (isRegistered && isValidated == 1) {

    if (numCartItems > 0) {
      document.express.submit();
    } else {
      alert("There are no items in your shopping cart.");
    }

  } else {
  
    if (isRegistered == 1 && isValidated == 0) {
      
      var js_loginForm = document.getElementById("loginForm");
      js_loginForm.style.display = "block";
      
      var js_passwordInput = document.getElementById("passwordInput");
      js_passwordInput.focus();
  
      alert("For your security, please confirm your account password before continuing.");
      
    } else {

      var js_loginForm = document.getElementById("loginForm");
      js_loginForm.style.display = "block";
      
      var js_usernameInput = document.getElementById("usernameInput");
      js_usernameInput.focus();
  
      alert("You must log in or register a new account before continuing.");
    
    }
    
  }
  
}

// display the checkout options
function displayCheckout() {

  var js_checkoutOptions = document.getElementById("checkoutOptions");
  js_checkoutOptions.style.display = "";
  
  var js_checkoutButton = document.getElementById("checkoutButton");
  js_checkoutButton.style.display = "none";

}

// submit the express checkout form
function placeOrder() {

  if (isValidated == 1) {
  
    document.placeorder.submit();
    
  } else {

    var js_loginForm = document.getElementById("loginForm");
    js_loginForm.style.display = "block";
      
    var js_passwordInput = document.getElementById("passwordInput");
    js_passwordInput.focus();
  
    alert("For your security, please confirm your account password before continuing.");
  
  }
  
}

// check session validation via Ajax and if valid, display asset
function deliverArticle(id) {

  var currentDate = new Date();
  var currentTs = currentDate.getTime();

  http.open("get", "webstore.php?amp_action=do_ajax_checkvalidate&articleid=" + id + "&seed=" + currentTs.toString(), true);
  http.onreadystatechange = handleDeliverArticleResponse;
  http.send(null);

}

function handleDeliverArticleResponse() {

  if (http.readyState == 4) {
  
    var response = http.responseText;
    var data = response.split("|");

    if (data[0] == "ok") {
    
      window.location.href = "storeasset.php?amp_action=article&articleid=" + data[1];

    } else {
    
      var js_loginForm = document.getElementById("loginForm");
      js_loginForm.style.display = "block";
      
      var js_passwordInput = document.getElementById("passwordInput");
      js_passwordInput.focus();
  
      alert("Session has timed out. For your security, please confirm your account password before continuing.");
    
    }

  }

}

// sets the right country on the view account page
function populateCountry(country) {

  var js_edituserCountry = document.getElementById("edituserCountry");
  var children = js_edituserCountry.childNodes;

  var optionIndex = 0;
  
  for (var i = 0; i < children.length; i++) {
  
    if (children[i].tagName == "option" || children[i].tagName == "OPTION") {
    
      if (children[i].value == country) {
      
        js_edituserCountry.selectedIndex = optionIndex;
        return;
        
      }

      optionIndex++;
    
    }
  
  }


}