/* readCookie() - this function is used to read a cookie stored with the browser when the page was sent by the server
 *
 * Arguments    : name - string representing the name of the cookie we want to find the value for
 *
 * Return       : value - the value of the cookie referenced by name argument
 *
 * Dependancies : this function depends on readCookie('cookiename') method
 */ 
function readCookie(name) 
{
     if (name == null)
          return null;
          
     var nameEQ = name + "=";
     var ca = document.cookie.split(';');
     for(var i=0;i < ca.length;i++)
     {
          var c = ca[i];
          while (c.charAt(0)==' ') c = c.substring(1,c.length);
          if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
     }
     return null;
}

function isInternetExplorer() {
     return (navigator.appName == 'Microsoft Internet Explorer');
}

function isChildWindow()
{
     return (window.opener != null);
}

function hasClientLoggedIn()
{
     // if the accountid cookie is present then the client is logged in on this browser
     return (readCookie('accountid') != null);
}

function hasViewCredits()
{
     var paid = readCookie('paid_tracker');
     var promo = readCookie('promo_tracker');
     var gift = readCookie('gift_tracker');
     
     var tcredits = 0;
     if (paid != null) { tcredits += paid; }
     if (promo != null)  { tcredits += promo; }
     if (gift != null) { tcredits += gift; }
          
     return (tcredits > 0)
}

function parseKeyValuePairsInQueryString(qString)
{
     if (qString == null)
          return null;
          
     if(qString.length <= 1)
          return null;

     var params  = qString.substring(1, qString.length);
     var keyValuePairs = new Array();
     
     for(var i=0; i < params.split("&").length; i++) 
     {
          keyValuePairs[i] = params.split("&")[i];
     }
     
     return keyValuePairs;
}

function getKey(keyValPair)
{
     if (keyValPair == null)
          return null;
          
     return keyValPair.split("=")[0];
}

function getValue(keyValPair)
{
     if (keyValPair == null)
          return null;
          
     return keyValPair.split("=")[1];
}

function hasBeenPurchasedForViewing()
{
     var keyValueArray = parseKeyValuePairsInQueryString(unescape(window.location.search));
     if (keyValueArray == null)
          return false;
          
     var movieid = null;
     for (var i = 0; i < keyValueArray.length; i++)
     {
          if (getKey(keyValueArray[i]) == 'movielib_id')
          {
               movieid = getValue(keyValueArray[i]);
               i = keyValueArray.length;
          }
     }
     
     return (readCookie(movieid) != null);
}

function checkPurchaseWindowAuthentication()
{    
     if ( ! isChildWindow() )
     {
          window.location='../php/notchildwindow.php';
     }
}

function checkUserAuthentication()
{
     // client has not logged in on this browser
     if ( ! hasClientLoggedIn() ) 
     {
          window.location='../lib/php/notloggedin.php';
     }
}

function checkMovieAuthentication()
{
     // if the client does not have any movie credits left
//   if ( ! hasViewCredits() )
//   {
//        window.location='../lib/php/noviewcredits.php';
//   }
     
     // if the movie credit view time has expired then we need to use another credit
     if ( ! hasBeenPurchasedForViewing() ) 
     {
          window.location='expiredmoviecredit.php';
     }
}

function authenticateMovieViewPurchaseForm(form)
{
     var movieurl = form.movielib_url.value;
     var movieid = form.movielib_id.value;
     var actionurl = form.action_url.value;
     var title = form.title.value;
     var poster = form.poster.value;
     var height = form.height.value;
     var width = form.width.value;
     
     var url = actionurl + "?movielib_id=" + movieid + "&" +
               "movielib_url=" + movieurl + "&" + "title=" + title +
               "&" + "poster=" + poster + "&" + "height=" + height +
               "&" + "width=" + width;
                     
     var nw = window.open(url, 'newwin', 'height=300, width=400');
     nw.moveTo(100,100);
}

/* initAuthentication() - this function is used as a driver to perform all page authentication. 
 *
 * Arguments    : authfuncname - name for specific type of authentication to do
 *
 * Return       : none
 *
 * Dependancies : this function depends on readCookie('cookiename') method
 */
function initAuthentication(authfunction)
{
     if (authfunction == 'userauth')
     {
          checkUserAuthentication();
     }
     
     if (authfunction == 'movieauth')
     {
          checkMovieAuthentication();
     }
     
     if (authfunction == 'purchasewindowauth')
     {
          checkPurchaseWindowAuthentication();
     }
}

function validateNewAccountForm(form)
{     
     var fnameVal = form.fname.value;
     if (fnameVal == "") {
          document.getElementById("fname_error").innerHTML = "'fname' must be set!";
          return false;
     }
     else if (fnameVal.length < 2) {
          document.getElementById("fname_error").innerHTML = "'fname' must be at least 2 characters!";
          return false;
     }
     
     var matchExp = /^[A-Za-z]+$/;
     
     var matchPos = fnameVal.match(matchExp);
     if (matchPos == null) {
          document.getElementById("fname_error").innerHTML = "'fname' must be alpha characters only! '" + fnameVal + "'";
          return false;
     }
     document.getElementById("fname_error").innerHTML = ""; 
  
     var emailVal = form.email.value;
     if (emailVal == "") {
          document.getElementById("email_error").innerHTML = "'email' must be set!";
          return false;
     }
     else if (emailVal.length < 5) {
          document.getElementById("email_error").innerHTML = "'email' must be at least 5 characters!";
          return false;
     }
     
     matchExp = /^[A-Za-z0-9._]+@[A-Za-z0-9._]+$/;
     
     matchPos = emailVal.match(matchExp);
     if (matchPos == null) {
          document.getElementById("email_error").innerHTML = "'email' has invalid syntax! '" + emailVal;
          return false;
     }
     
     var url = "lib/php/isValidEmail.php?email=" + emailVal;
     if (!synchronousServerValidation("email_error", url)) {
          return false;
     }
     
    document.getElementById("email_error").innerHTML = ""; 
  
     var passVal = form.passwd.value;
     if (passVal == "") {
          document.getElementById("passwd_error").innerHTML = "'password' must be set!";
          return false;
     }
     else if (passVal.length < 6) {
          document.getElementById("passwd_error").innerHTML = "'password' must be at least 6 characters!";
          return false;
     }
     
     matchExp = /^\S+$/;
     
     matchPos = passVal.match(matchExp);
     if (matchPos == null) {
          document.getElementById("passwd_error").innerHTML = "'password' must be non whitespace characters only! '" + passVal + "'";
          return false;
     }
     
     document.getElementById("passwd_error").innerHTML = ""; 
     
     var confPassVal = form.confpasswd.value;
     if (passVal != confPassVal) {
          document.getElementById("confpasswd_error").innerHTML = "'confpasswd' must match password!";
          return false;
     }
     
     document.getElementById("confpasswd_error").innerHTML = ""; 

     var zipcodeVal = form.zipcode.value;
     if (zipcodeVal == "") {
          document.getElementById("zipcode_error").innerHTML = "'zipcode' must be set!";
          return false;
     }
     else if (zipcodeVal.length != 5) {
          document.getElementById("zipcode_error").innerHTML = "'zipcode' must be at least 5 characters!";
          return false;
     }
     
     matchExp = /^\d+$/;
     
     matchPos = zipcodeVal.match(matchExp);
     if (matchPos == null) {
          document.getElementById("zipcode_error").innerHTML = "'zipcode' must be digits characters only! '" + zipcodeValVal + "'";
          return false;
     }
     
     var promoidVal = form.promoid.value;
     if (promoidVal.length > 0) 
     { 
          url = "lib/php/isValidPromoCode.php?promoid=" + promoidVal;
          if (!synchronousServerValidation("promoid_error", url)) {
               return false;
          }
          document.getElementById("promoid_error").innerHTML = "";
     }
     
     return true;
}

function validateForgotPasswordForm(form)
{     
     var emailVal = form.email.value;
     if (emailVal == "") {
          document.getElementById("email_error").innerHTML = "'email' must be set!";
          return false;
     }
     else if (emailVal.length < 5) {
          document.getElementById("email_error").innerHTML = "'email' must be at least 5 characters!";
          return false;
     }
     
     matchExp = /^[A-Za-z0-9._]+@[A-Za-z0-9._]+$/;
     
     matchPos = emailVal.match(matchExp);
     if (matchPos == null) {
          document.getElementById("email_error").innerHTML = "'email' has invalid syntax! '" + emailVal;
          return false;
     }
     
     var url = "lib/php/isExistingEmailAddress.php?email=" + emailVal;
     if (!synchronousServerValidation("email_error", url)) {
          return false;
     }
     
    document.getElementById("email_error").innerHTML = ""; 
       
     return true;
}

function processPurchaseType(form)
{
     if (form == null || form.purchasetype == null) 
     {
           return false;
     }
     
     form.action="purchasemovie.php";
     
     if (!isInternetExplorer() && form.purchasetype instanceof HTMLInputElement) {
          
          if (!form.purchasetype.checked) 
          {
               return false;
          }
          
          if (form.purchasetype.value == "VOD") 
          {
               if (form.amount.value > 0) {
                    form.action="https://www.paypal.com/cgi-bin/webscr";
                    if (isChildWindow()) {
                         window.moveTo(0,0);
                         window.resizeTo(screen.width,screen.height);          
                    }
               }
          }
          return true;
     } 
  
     for (var i = 0; i < form.purchasetype.length; i++) {
          
          if (form.purchasetype[i].checked) {        
               if (form.purchasetype[i].value == "VOD") {
                    if (form.amount.value > 0) {
                         form.action="https://www.paypal.com/cgi-bin/webscr";
                         if (isChildWindow()) {
                              window.moveTo(0,0);
                              window.resizeTo(screen.width,screen.height);
                         }
                         i = form.purchasetype.length;
                    }
               }               
          }
     }
 
     return true;
}

function setPurchaseViewCreditFormParameters(form)
{
     var account = readCookie('accountid');
}


