﻿// JScript File
var emailValidation = new Boolean(true);
var TCValidation = new Boolean(true);
var FormValidation = "OK-";

function SubmitContactForm_ShowError(_error)
{
  	SetInnerText(document.getElementById("FormError"),_error);

}

function SubmitContactForm_Wrapped(args, context, m_controlMode)
{
  //debugger;
	try
	{
	    var messageDiv = document.getElementById("FormError");
	    
	    switch(FormVerification())
	    {
	      case "OK-":
	        SetInnerText(document.getElementById("FormError"),"");
	        ContactForm_CallbackTrigger();
	        break;	      
	      case "OK-EMAIL-":	        
	        SetInnerText(messageDiv,"* Please enter a valid Email Address");
	        break;
	      case "OK-T&C":
	        SetInnerText(messageDiv,"* You must read and accept the Terms and Conditions before continuing");
	        break;
	      case "OK-EMAIL-T&C":
	        SetInnerText(messageDiv,"* Please enter a valid Email Address and then read and accept the Terms and Conditions before continuing");
	        break;
	      case "OK-QUAN":
	        SetInnerText(messageDiv,"* You must select a minimum of 1 license");
	        break;
	      default:
	        SetInnerText(messageDiv,"* Please Fill in All the Required Fields");
	        break;
	    }
	    FormValidation = "OK-";
	}
	catch(e)
	{
		alert('ERROR: Sorry, this form is unavailable at this time');
	}
}

function FormVerification()
{

	// ensure that the necessary fields are filled in
	var digit = 0;
	var tb;
	for(digit=0; (tb = document.getElementsByTagName("input")[digit]); digit++) 
	{
		if(tb.className == "contactFormTb" && tb.value == "")
		    FormValidation += "REQ-"
		switch(tb.id)
		{
		  case "ContactForm1_emailTextBox":
		    // validate as an email
			if(!echeck(tb.value))
			  FormValidation += "EMAIL-";
		    break;
		  case "ContactForm1_AcceptT&C":
		    if(tb.checked == false && document.getElementById("ContactForm1_PaymentRadioButtonList_1").checked == true)
		      FormValidation += "T&C";
		    break;
		  case "ContactForm1_licenseAmmountTextBox":
		    if(tb.value == "" || tb.value == "0")
		      FormValidation += "QUAN";
		    break;
		  default:
		    break;
		}
	}
	//debugger;
	return FormValidation;
}

function ContactForm_CallbackTrigger_Wrapped(cbreference)
{
  //debugger;
	try
	{
		//clear the textbox values
		var textboxvalues = new Array();
		textboxvalues[0] = "";
		textboxvalues[1] = "";
		textboxvalues[2] = "";
		textboxvalues[3] = "";
		textboxvalues[4] = "";
		textboxvalues[5] = "";
		
		var num = 0;
		var digit = 0;
		var tb;
		for(digit=0; (tb = document.getElementsByTagName("input")[digit]); digit++) 
		{
			if(tb.className == "contactFormTb" || tb.className == "contactFormTbNotRequired")
			{
				textboxvalues[num] = tb.value;
				num++;
			}
		}
		
//		var digitTA = 0;
//		var tbTA = 0;
//		for(digitTA=0; (tbTA = document.getElementsByTagName("textarea")[digitTA]); digitTA++) 
//		{
//			if(tbTA.className == "contactUsDescription")
//				textboxvalues[4] = document.getElementsByTagName("textarea")[digitTA].value;
//		}

        // set the payment mode
        // 1. Free Trial
        // 2. Full Payment
        // 3. HK Account
        var mode;        
        var temp1 = parseInt(textboxvalues[5]);
        
        if(temp1 <= 9999999999)//10)
          mode = "Trial";
        else
          mode = "Payment";
          
        if(document.getElementById("ContactForm1_PaymentRadioButtonList_1").checked == true)
          mode = "Account"
		
	    // Build the URL ready to send for the callback - this will be used for the payment done/failed links
	    //debugger;
	    var pathArray = window.location.pathname.split( '/' );
	    var newURL = window.location.protocol + "//" + window.location.host + "/" + pathArray[1];

		
		var args = 'Mode='+mode+'|Telephone='+textboxvalues[4]+'|Email='+textboxvalues[3]+'|FirstName='+textboxvalues[1]+'|LastName='+textboxvalues[2]+
		           '|Organization='+textboxvalues[0]+'|Description='+textboxvalues[5]+'|NumberOfUsers='+textboxvalues[5]+
		           '|PrivateSpaceName='+textboxvalues[6]+'|Cost='+textboxvalues[7]+'|Url='+newURL;
		eval(cbreference);
	}
	catch(e)
	{
	}
}

function ContactForm_CallbackDone_Wrapped(args)
{
  // Check for a session time out before completing the callback
  if (CheckSessionTimeout())
    return;
  
var allArgs = args;
var argList;
if(args.indexOf('|') != -1)
{
  argList = args.split('|');
  args = argList[0];
}
switch(args)
{
  case "sign in":
    ToggleLoginControl();
    
    break;
  case "ps sign in":
    //ToggleLoginControl();
      var qs = allArgs.substring(args.length);
      var returnURL = escape(window.location.toString() + '?' + qs);
      // Save the current URL on Session for returning to
      SetSessionProperty("ReturnURL", returnURL);
      // Redirect the user to the Sign In / Sign Up Page 
      window.location = "registerps.aspx";
    break;
  case "ps sign up":
    //redirectToSignInSignUpPage('sign up')
    // get query string
    var qs = allArgs.substring(args.length);
    var returnURL = escape(window.location.toString() + '?' + qs);
  
    // Save the current URL on Session for returning to
    SetSessionProperty("ReturnURL", returnURL);
  
    // Redirect the user to the Sign In / Sign Up Page 
    window.location = "registerps.aspx";
    break;
  case "sign up":
    //redirectToSignInSignUpPage('sign up')
    var returnURL = escape(window.location.toString());
  
    // Save the current URL on Session for returning to
    SetSessionProperty("ReturnURL", returnURL);
  
    // Redirect the user to the Sign In / Sign Up Page 
    window.location = "register.aspx";
    break;
  case "Trial":
    SetSessionProperty("ConfirmationType", args);
    window.location = "PrivateSpaceConfirmation.aspx";     
    break;
  case "Account":
    SetSessionProperty("ConfirmationType", args);
    window.location = "PrivateSpaceConfirmation.aspx";     
    break;
  case "Payment":
    window.location= "Confirmation.aspx";  
    break;    
  case "Duplicate":
    var messageDiv = document.getElementById("FormError");
    SetInnerText(messageDiv,"* You have already set up a single user Private Space.  Please increase the number of users and try again.");
    break; 
}

//	try
//	{
//		var digit = 0;
//		var tb = 0;
//		for(digit=0; (tb = document.getElementsByTagName("input")[digit]); digit++) 
//		{
//			if(tb.className == "contactFormTb" || tb.className == "contactFormTbNotRequired")
//				tb.value = "";
//		}
//		
//		var digitCB = 0;
//		var tbCB = 0;
//		for(digitCB=0; (tbCB = document.getElementsByTagName("textarea")[digitCB]); digitCB++) 
//		{
//			if(tbCB.className == "contactUsDescription")
//				tbCB.value = "";
//		}
//			
//		// notify user
//		document.getElementById("FormError").innerText = "Thank you " + args + ", your details are submitted";
//	}
//	catch(e)
//	{
//	}
}

function ContactForm_ProcessCallBackError_Wrapped(args, context, client)
{
}

function echeck(str) 
{
	// simple javascript email validation...
	var at="@"
	var dot="."
	var lat=str.indexOf(at)
	var lstr=str.length
	var ldot=str.indexOf(dot)
	if (str.indexOf(at)==-1)
	{
		 return false
	}
	if (str.indexOf(at)==-1 || str.indexOf(at)==0 || str.indexOf(at)==lstr)
	{
		 return false
	}
	if (str.indexOf(dot)==-1 || str.indexOf(dot)==0 || str.indexOf(dot)==lstr)
	{
			return false
	}
	if (str.indexOf(at,(lat+1))!=-1)
	{
			return false
	}
	if (str.substring(lat-1,lat)==dot || str.substring(lat+1,lat+2)==dot)
	{
			return false
	}
	if (str.indexOf(dot,(lat+2))==-1)
	{
			return false
	}
	if (str.indexOf(" ")!=-1)
	{
			return false
	}
	return true					
}


function contactForm_textHighlight(_id)
{
  document.getElementById(_id).className = "PrivateSpacePurchase_Highlight";
}

function contactForm_textUnhighlight(_id)
{
  document.getElementById(_id).className = "PrivateSpacePurchase";
}



function CheckNumberOfLicenses2(elem)
{
//debugger;
    if (/[^\d]/g.test(elem.value))
       elem.value = elem.value.replace(/[^\d]/g, '');
    if(parseInt(elem.value) > 5000)
       elem.value = elem.value.substring(0,elem.value.length - 1);    
}




function CheckNumberOfLicenses(_textBoxId)
{
//debugger;
  // get the text box element
  var textBox = document.getElementById("ContactForm1_" + _textBoxId);
  if(textBox != null)
  {
    // check if the key press is for a number- if so, then return true
    if(event.keyCode > 47 && event.keyCode < 58)
    {     
      UpdatePageLayout(textBox)
      return true;
    }
    else
      return false;
  }
}

function UpdatePageLayout(_textBox, _hypAccount)
{
//debugger;
    var hostElement = document.getElementById("ContactForm1_KGTopTopicsControl");

    var disclaimer = document.getElementById("ContactForm1_disclaimerText");  
    var monthlyCost = document.getElementById("ContactForm1_calculatedMonthlyCost");
    var privateSpaceName = document.getElementById("ContactForm1_PrivateSpaceName"); 
    
    var remove;
    
    // this is a bit of a hack
    //var temp1 = event.keyCode - 48; // minus 48 from the keyCode to get the integer value     
    //var temp2 = _textBox.value;
    
    //var temp3 = temp2 + temp1;  // add the existing contents of the text box with the newly added number     
    
    temp3 = parseInt(document.getElementById(_textBox).value); // make sure we convert the string into an int i.e.  "13" -> 13
    
    // If the number of licenses is greater than 10
    //if(document.getElementById(_textBox).value != '1' && document.getElementById(_textBox).value != '')//(event.keyCode != 49)
    if(temp3 > 9999999999)//10)//(event.keyCode != 49)
    {    
        //
        // start by removing any items on the page we don't want
        //
        
        // Remove the 'start free trial' link if it's on the page
        var lnkStartFreeTrial = document.getElementById('FreeTrialPrivateSpace');
        if(lnkStartFreeTrial != null)
        {
          purge(lnkStartFreeTrial);
          lnkStartFreeTrial.parentNode.removeChild(lnkStartFreeTrial);
        }
          
        // Show the payment radio buttons          
        document.getElementById("ContactForm1_PaymentRadioButtonList").className = "PaymentMethods_Show";
    
        if(document.getElementById("ContactForm1_PaymentRadioButtonList_0").checked == true)  //card payment
        {
          //
          // The user might have changed radio button options so we need to check for any 'account payment' objects
          // which may be on the screen and delete them.
          //
          
          // Hide the 'Terms & Conditions' box if it's visible
          var termsAndConditions = document.getElementById("ContactForm1_TermsAndConditionsDiv");
          termsAndConditions.className = "TermsAndConditions_Hide"; 
          
          // Remove the 'apply for HK account' link if its on the page
          var lnkApplyForHKAccount = document.getElementById("ApplyHyperknowledgeAccount");
          if(lnkApplyForHKAccount != null)
          {
            purge(lnkApplyForHKAccount);
            lnkApplyForHKAccount.parentNode.removeChild(lnkApplyForHKAccount);
          }
          
          //
          // Now add and show any controls relevent for card payment - these are: updating the disclaimer, and adding the accept and decline links
          //
          
          //update the disclaimer
          disclaimer.innerHTML = "<p>Please confirm that you want to setup a Private Space with the details above.</p><p>The first payment will be taken immediately and then on the 12th of each month.</p>";
          
          // Check if the links are already on the page - only need to check one (if thats there, then the other is and vice versa)
          var lnkCard = document.getElementById("SubscribePrivateSpace_Agree");
          if(lnkCard == null)
          {
            // Add the 'agree to subscribe' link to the page
            var lnkAgree;  
            lnkAgree = document.createElement("div");
            lnkAgree.setAttribute("id","SubscribePrivateSpace_Agree");
            //InsertAdjacentElement(hostElement, "beforeend", lnkAgree);
            hostElement.appendChild(lnkAgree);
            //hostElement.insertAdjacentElement("beforeEnd", lnkAgree);
            var AgreeLink = document.getElementById("SubscribePrivateSpace_Agree")
            
            AgreeLink.className = "PrivateSpacePurchase";
            AgreeLink.onclick = function(){SubmitContactForm()};
            AgreeLink.onmouseover = function(){contactForm_textHighlight('SubscribePrivateSpace_Agree')};      
            AgreeLink.onmouseout = function(){contactForm_textUnhighlight('SubscribePrivateSpace_Agree')};
            AgreeLink.innerHTML = "<u>Yes, Please take me to the payment screens</u>";
            //lnkAgree = document.getElementById("ContactForm1_KGTopTopicsControl").insertAdjacentElement("beforeEnd", lnkAgree);
            lnkAgree = null;
           
            // Add the 'decline to subscribe' link to the page 
            var lnkDecline;
            lnkDecline = document.createElement("div");
            lnkDecline.setAttribute("id","SubscribePrivateSpace_Decline");
            lnkDecline.className = "PrivateSpacePurchase";
            //lnkDecline.setAttribute("onclick", "SubmitContactForm()");
            lnkDecline.onmouseover = function(){contactForm_textHighlight('SubscribePrivateSpace_Decline')};
            lnkDecline.onmouseout = function(){contactForm_textUnhighlight('SubscribePrivateSpace_Decline')};
            lnkDecline.innerHTML = "<u>No, Please take me to the Home Page</u>";
            lnkDecline = InsertAdjacentElement(document.getElementById("ContactForm1_KGTopTopicsControl"), "beforeend", lnkDecline);
            //lnkDecline = document.getElementById("ContactForm1_KGTopTopicsControl").insertAdjacentElement("beforeEnd", lnkDecline);
          }
          
          // update the monthly cost and privatespace name boxes
          monthlyCost.value = "$" + document.getElementById(_textBox).value;
          if(privateSpaceName.disabled == true)
          {
            privateSpaceName.value = "My Categories";
            privateSpaceName.disabled = false;     
          }  
    
        }
        else // account payment
        {
           //
          // The user might have changed radio button options so we need to check for any 'card payment' objects
          // which may be on the screen and delete them.
          //
          
          // check for and remove the accept link
          var lnkAccept = document.getElementById("SubscribePrivateSpace_Agree");
          if(lnkAccept != null)
          {
            purge(lnkAccept);
            lnkAccept.parentNode.removeChild(lnkAccept);
          }
          
          // check for and remove the decline link  
          var lnkDecline = document.getElementById("SubscribePrivateSpace_Decline");
          if(lnkDecline != null)
          {
            purge(lnkDecline);
            lnkDecline.parentNode.removeChild(lnkDecline);
          }
          
          // update the disclaimer
          disclaimer.innerHTML = "<p>We will contact you shortly regarding this request.  Please accept the terms and conditions below and click the following link.</p>";
          
          // show the terms and conditions box
          var termsAndConditions = document.getElementById("ContactForm1_TermsAndConditionsDiv");
          termsAndConditions.className = "TermsAndConditions_Show"; 
          
          
          // Check if the link is already on the page
          var lnkAccount = document.getElementById("ApplyHyperknowledgeAccount");
          if(lnkAccount == null)
          {
            var lnkHKAccount;  
            lnkHKAccount = document.createElement("div");
            lnkHKAccount.setAttribute("id","ApplyHyperknowledgeAccount");
            lnkHKAccount.className = "PrivateSpacePurchase";
            lnkHKAccount.onclick = function(){SubmitContactForm()};
            lnkHKAccount.onmouseover = function(){contactForm_textHighlight('ApplyHyperknowledgeAccount')};      
            lnkHKAccount.onmouseout = function(){contactForm_textUnhighlight('ApplyHyperknowledgeAccount')};
            lnkHKAccount.innerHTML = "<u>Please setup an account and invoice me</u>";
            lnkHKAccount = InsertAdjacentElement(document.getElementById("ContactForm1_KGTopTopicsControl"), "beforeend", lnkHKAccount);
            //lnkHKAccount = document.getElementById("ContactForm1_KGTopTopicsControl").insertAdjacentElement("beforeEnd", lnkHKAccount);
          }  
          
          monthlyCost.value = "$" + document.getElementById(_textBox).value;
          if(privateSpaceName.disabled == true)
          {
            privateSpaceName.value = "My Categories";
            privateSpaceName.disabled = false;     
          }  
        }
    }
    else
    {       
        var termsAndConditions = document.getElementById("ContactForm1_TermsAndConditionsDiv");
        if(termsAndConditions != null)
          termsAndConditions.className = "TermsAndConditions_Hide"; 
              
        remove = document.getElementById("ApplyHyperknowledgeAccount");
        if(remove != null)
        {
          purge(lnkDecline);
          remove.parentNode.removeChild(remove);
        }
    
        document.getElementById("ContactForm1_PaymentRadioButtonList").className = "PaymentMethods_Hide";
        
        if(disclaimer != null)
        {
          disclaimer.innerHTML = "<p>Please confirm that you want to setup a Private Space with the details above.</p>";
        }
        
        var agree = document.getElementById('SubscribePrivateSpace_Agree');
        // remove the docked item from the page
        if(agree != null)
        {
          purge(agree);
          agree.parentNode.removeChild(agree); 
        }
        
        var decline = document.getElementById('SubscribePrivateSpace_Decline');
        // remove the docked item from the page
        if(decline != null)
        {
          purge(decline);
          decline.parentNode.removeChild(decline); 
        }
              
        if(document.getElementById('FreeTrialPrivateSpace') == null)
        {
            var controlToInsert3;  
            controlToInsert3 = document.createElement("div");
            controlToInsert3.setAttribute("id","FreeTrialPrivateSpace");
            controlToInsert3.className = "PrivateSpacePurchase";
            controlToInsert3.onclick = function(){SubmitContactForm()};
            controlToInsert3.onmouseover = function(){contactForm_textHighlight('FreeTrialPrivateSpace')};      
            controlToInsert3.onmouseout = function(){contactForm_textUnhighlight('FreeTrialPrivateSpace')};
            controlToInsert3.innerHTML = "<u>Yes, Please start my free 30-day trial now</u>";
            controlToInsert3 = InsertAdjacentElement(document.getElementById("ContactForm1_KGTopTopicsControl"), "beforeend", controlToInsert3);
            //controlToInsert3 = document.getElementById("ContactForm1_KGTopTopicsControl").insertAdjacentElement("beforeEnd", controlToInsert3);
        }
                 
        // update the monthly cost and privatespace name boxes
        monthlyCost.value = "$ " + document.getElementById(_textBox).value;
        monthlyCost.value += " (30-day free trial first)";// + document.getElementById(_textBox).value;
        if(temp3 <= 1)
        {
          privateSpaceName.value = "Not applicable for " + document.getElementById(_textBox).value + " user(s)";
          privateSpaceName.disabled = true; 
        }
        else if(privateSpaceName.disabled == true)
        {
            privateSpaceName.value = "My Categories";
            privateSpaceName.disabled = false;     
        } 
    }  
    
    hostElement = null;  
}

function SetupHyperknowledgeAccount()
{
  var disclaimer = document.getElementById("ContactForm1_disclaimerText");
  
   if(disclaimer != null)
      disclaimer.innerHTML = "<p>We will contact you shortly regarding this request.  Please accept the terms and conditions below and click the following link.</p>";
       
  var termsAndConditions = document.getElementById("ContactForm1_TermsAndConditionsDiv");
  termsAndConditions.className = "TermsAndConditions_Show";          
}

function PrivateSpaceTryAgain()
{  
    var currentLocation = window.location.href;
    var currentPage = currentLocation.substring(currentLocation.indexOf("orderFailed"));
    var hostURLForRedirect = currentLocation.substring(0, currentLocation.indexOf("orderFailed"));
    window.location = hostURLForRedirect + 'PrivateSpace.aspx';
}




