var MainAreaID = -1;

function setMainAreaID(mainAreaIDValue) {
  MainAreaID = mainAreaIDValue;
}

function openOverlay() {
  var api = $("#overlay").overlay();
  api.load();
}

function createXMLHttp() {
  var myobj;
  try { myobj = new ActiveXObject("Msxml2.XMLHTTP.4.0"); }
  catch (ex) {
    try { myobj = new ActiveXObject("Msxml2.XMLHTTP.3.0"); }
    catch (ex) {
      try { myobj = new ActiveXObject("Msxml2.XMLHTTP"); }
      catch (ex) {
        try { myobj = new ActiveXObject("Microsoft.XMLHTTP"); }
        catch (ex) {
          try { myobj = new XMLHttpRequest(); }
          catch (ex) { myobj = false; alert("Could not load XMLHTTP component"); } 
        } 
      } 
    } 
  }
  return myobj;
}

function busyCursor() {
  try { document.body.style.cursor = "busy"; }
  catch (e) { alert(e); }
}

function regularCursor() {
  try { document.body.style.cursor = "auto"; }
  catch (e) { alert(e); }
}

function showLoading() {
	
  busyCursor();
  var loaddiv = document.getElementById("basketHolder");
   
  if (loaddiv) {
	 
    loaddiv.style.display = "";
    loaddiv.innerHTML = "<span class=\"LEFTtext\">Loading...</span>";
  }
  loaddiv = null;
}

function hideLoading() {
  regularCursor();
  var loaddiv = document.getElementById("basketHolder");
  if (loaddiv) {
    loaddiv.style.display = "none";
  }
  loaddiv = null;
}

var alertBasketResponse = function(oXML, redir) {
	document.getElementById("basketHolder").style.display = "";
  	document.getElementById("basketHolder").innerHTML = oXML.responseText;
  
  regularCursor();
  oXML = null;

  if (redir) { window.location = "wines.asp?MainAreaID="+ MainAreaID; }
};

var alertForgetResponse = function(oXML) {
  alert("Password has been e-mailed. You should receive it momentarily");
}

var alertLoginResponse = function(oXML) {
	
 if (oXML.responseText == "Authentication for Member failed. Please try again") {
    if (confirm("Authentication for Member failed. Click 'OK' to be e-mailed your password reminder.")) {
      if (document.getElementById("username").value != "") {
        loadPage('/South%20Africa/login/forgot_password.asp', 'txtUsername=' + document.getElementById("username").value, alertForgetResponse);
      }
    }
  } 
  else {
    if (oXML.responseText.indexOf("wines.asp?") == 0){
      window.location = oXML.responseText;
	} 
	else {
      if (oXML.responseText.indexOf("wines.asp?") == -1){
	    window.location = oXML.responseText;
	  }
      else {
        window.location = "wines.asp?MainAreaID=" + MainAreaID;
	  }
    }
  }
}


var alertRegistrationResponse = function(oXML) {
  var blnRedirect = true;
  if (oXML.responseText == "ERROR") {
    document.getElementById("username").value = document.getElementById("txtEmailaddress").value;
    document.getElementById("sameloginoverlay").style.display = "";
	//alert("You're already a member on cybercellar.com! Use your existing password to login");
    //openOverlay();
    document.getElementById("redir").value = "true";
    document.getElementById("password").focus();
    blnRedirect = false;
  }
  regularCursor();
  oXML = null;

  if (blnRedirect) {
    loadPage("login.asp", "action=login&MainAreaID=" + MainAreaID + "&username=" + document.getElementById("txtEmailaddress").value + 
	         "&password=" + document.getElementById("txtPasswordConfirm").value + "&OverrideRedirectTo=signup.asp", 
			 alertLoginResponse);
  }
}

function postRegistration() {

  var registrationData;
  registrationData = "action=INSERT&txtEmailaddress=" + document.getElementById("txtEmailaddress").value + "&txtName=" + document.getElementById("txtName").value + "&txtSurname=" + document.getElementById("txtSurname").value + "&txtPasswordConfirm=" + document.getElementById("txtPassword").value;

  if (document.getElementById("txtEmailaddress").value != document.getElementById("txtEmailAddressConfirm").value) {
    alert("Your email address does not match the confirmed email address!");
  } else {
    if (document.getElementById("txtPassword").value != document.getElementById("txtPasswordConfirm").value) {
      alert("Your password does not match the confirmed password!");
    } else {
      if (document.getElementById("txtName").value == "") {
        alert("Please supply us with your First Name!");
      } else {		  
        if (document.getElementById("txtSurname").value == "") {
          alert("Please supply us with your Surname!");
        } else {
		  if (document.getElementById("txtEmailaddress").value == "") {
         	alert("Please supply us with your Email!");
          } else {
			
			loadPage("register.asp", registrationData, alertRegistrationResponse)
		  }	
        }
      }
    }
  }
};


function validate() {
  if (document.getElementById("txtDeliveryTo").value == "") {
    alert("Please enter a Recipient of this order!");
  } else {
    if (document.getElementById("txtContactNumber").value == "") {
      alert("Please enter a valid Contact Number!");
    } else {
      if (document.getElementById("txtAddress").value == "" || document.getElementById("txtAddress").value.length < 10) {
        alert("Please enter a valid Delivery Address!");
      } else {
        if (document.getElementById("txtCity").value == "") {
          alert("Please enter a City!");
        } else {
          if (document.getElementById("txtCountry").value == "") {
            alert("Please enter a Country!");
          } else {
            if (document.getElementById("txtPostalCode").value == "") {
              alert("Please enter a Postal Code!");
            } else {
              document.frmCheckout.submit();
            }
          }
        }
      }
    }
  }
}

function checkout(loggedIN) {
  if (loggedIN) {
    //if (document.getElementById("country").value != 0){
    window.location = "https://www.cybercellar.com/mischa/checkout.asp?MainAreaID=" + MainAreaID;
    //}
    // else {
    //     alert("Please choose a Region to continue checking out!");
    //}
  }
  else {
    //loadPage("login.asp","MainAreaID=13",alertBasketResponse);
    alert("To Continue Please log in with your username / password and member code");
  }
}

function logOut() {
  
  setMainAreaID(14);
  loadPage("wines.asp", "action=logout&MainAreaID=" + MainAreaID, alertLoginResponse);
   
}

function logIn() {
 var allFeatures = "redir=" + document.getElementById("redir").value + "&action=login&MainAreaID=" + MainAreaID + "&username=" + document.getElementById("username").value + "&password=" + document.getElementById("password").value + "&membercode=" + document.getElementById("membercode").value;
 
 loadPage("login.asp", allFeatures, alertLoginResponse);
 

}




function ReadCookie(cookieName) {
  var theCookie = "" + document.cookie;
  var ind = theCookie.indexOf(cookieName);
  if (ind == -1 || cookieName == "")
    return "";
  var ind1 = theCookie.indexOf('&', ind);

  if (ind1 == -1)
    ind1 = theCookie.indexOf(';', ind);

  if (ind1 == -1)
    ind1 = theCookie.length;
  return unescape(theCookie.substring(ind + cookieName.length + 1, ind1));
}


function closespan() {
  document.getElementById("logginMSGbox").style.display = "none";
}
function closespanLogin() {
  document.getElementById("sameloginoverlay").style.display = "none";
}

function addToBasket(WineID, PPBottle, WineName, QTY) {
 
  var loggedinstatus = ReadCookie('LoggedIN');
  if (loggedinstatus != "Y") {
    document.getElementById("logginMSGbox").style.display = "";
	
  }

  else {
    
    loadPage("basket.asp", "action=add&MainAreaID=" + MainAreaID + "&WineID=" + WineID + "&PPBottle=" + PPBottle + "&WineName=" + WineName + "&Wine_QTY=" + QTY, alertBasketResponse);
    
  }
 
}
function removeAllFromBasket() {
  if (confirm("Are You sure you want to remove ALL basket items?")) {
    loadPage("basket.asp", "action=removeall&MainAreaID=" + MainAreaID, alertBasketResponse);
  }
}

var space = / /g
function loadPage(page, data, ldfunction) {
	
  if (page != "register.asp") { showLoading();  }
  var xmlhttp = createXMLHttp();
  	if (xmlhttp) {
   		xmlhttp.open("POST", page, true);
    	if (data != "") {
     		xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
      		data = data.replace(space, "%20");
			//alert(data);
    	}

    	var redir = false;
    	try {
      		redir = document.getElementById("redir").value
    	} catch (e) {}

    	xmlhttp.onreadystatechange = function() {
			//alert('loading1');
      		if (xmlhttp.readyState == 4) {
				//alert('loading2');
				ldfunction(xmlhttp, redir);
        		xmlhttp = null;
      		}
    	}
	
	busyCursor();
    xmlhttp.send(data);
	//alert('loading3');
  }
}

function changeMainArea(MainAreaID) {
  window.location = "wines.asp?MainAreaID=" + MainAreaID;
};

function calculatePrice(WineID, PPBottle, CurrencySymbol) {
  if (PPBottle == 'NA') {
    document.getElementById("perBottle" + WineID).innerHTML = "N/A";
    document.getElementById("per6Bottle" + WineID).innerHTML = "N/A";
    document.getElementById("per12Bottle" + WineID).innerHTML = "N/A";
  }
  else {
    document.getElementById("perBottle" + WineID).innerHTML = currencyFormatter(PPBottle, CurrencySymbol);
    document.getElementById("per6Bottle" + WineID).innerHTML = currencyFormatter(((PPBottle * 1) * 6), CurrencySymbol);
    document.getElementById("per12Bottle" + WineID).innerHTML = currencyFormatter((PPBottle * 12), CurrencySymbol);
  }
};

function currencyFormatter(value, CurrencySymbol) {
  var dotspot, workspot, output, flag;
  //2 digit rounding simulator
  value = (Math.round(value * 100)) / 100;
  value = value.toString();
  //Add cents if required
  if (value.indexOf(".") == -1) {
    value = value.concat(".00");
  }
  dotspot = value.indexOf(".");
  workspot = dotspot;
  flag = true;
  //Add comma every 3 digits
  while (flag) {
    workspot = workspot - 3;
    if (workspot > 0) {
      var part1 = value.substring(0, workspot)
      var part2 = value.substring(workspot, value.length)
      value = part1 + "," + part2
      workspot = value.indexOf(",");
    }
    else {
      flag = false;
    }
  }
  dotspot = value.indexOf(".");
  if (value.substring(dotspot, value.length).length < 3) {
    value = value.concat("0");
  }
  output = CurrencySymbol + " " + value
  return output;
}

function displayShippingCost(value, symbol) {
  document.getElementById("displayShippingCost").innerHTML = currencyFormatter(value, symbol)
  document.getElementById("displayTotal").innerHTML = currencyFormatter((parseFloat(document.getElementById("hdnTotal").value)), symbol)
}



function closespan2(){
	document.getElementById("deliveryinfo").style.display = "none";
}

function openareasbox(){
	document.getElementById("deliveryinfo").style.display = "";
}
