/*
** $Id: hybrid2-belvoir.js,v 1.1.1.1 2009/10/07 02:57:23 iain Exp $
** $Source: /usr/local/share/cvsroot/BelvoirWebsiteSeason2010/fragments/hybrid2-belvoir.js,v $
**
*/


function belvoir_init () {

  // iemac fixes
  if (navigator.userAgent.indexOf('MSIE')>0 && navigator.userAgent.indexOf('Mac')>0) {
    x = document.getElementById("navul").getElementsByTagName('UL');
    for (i=0; i<x.length; i++) {
      x[i].style.marginTop = "-13px";
    }

    y = document.getElementById("navul").getElementsByTagName('LI');
    for (i=0; i<y.length; i++) {
      if (y[i].className == 'sel') {
        y[i].getElementsByTagName('A').item(0).style.borderBottom = "2px solid white";
      }
    }
    y[1].style.width = "6.2em";
    y[9].style.width = "7.2em";
    
    //pullhead

    //document.getElementById('tabs').style.marginTop = "20px";
  }
  
  //iewin fixes
  if (navigator.userAgent.indexOf('MSIE')>0 && navigator.userAgent.indexOf('Win')>0) {
    x = document.getElementById("navul").getElementsByTagName('A');
    for (i=0; i<x.length; i++) {
      x[i].style.display = "inline";
    }
    y = document.getElementById("navul").getElementsByTagName('UL');
    for (i=0; i<y.length; i++) {
      if (navigator.appVersion.indexOf('MSIE 6')>0) {
        y[i].style.left = "0em";
      }
      else if ( navigator.appVersion.indexOf('MSIE 5')>0) {
        y[i].style.left = "-16px";
      }
    }
    
    //safari fixes
    if (navigator.userAgent.indexOf('Safari')>0) {

    }
    
  }
  
  // javascript dom extras for nav in msie
  if (document.getElementById) {

    var navRoot = document.getElementById("navul");
    
    for (i=0; i<navRoot.childNodes.length; i++) {
      node = navRoot.childNodes[i];
      if (node.nodeName=="LI" && node.getElementsByTagName('UL').length>0) {
        if (document.all&&document.getElementById) { //msie
          node.onmouseover=function() {
            this.className+=" over";
          }
          node.onmouseout=function() {
            this.className=this.className.replace(" over", "");
          }
        }
        else if ( (navigator.userAgent.indexOf('Konqueror') > 0 || navigator.userAgent.indexOf('Gecko') > 0 ) && navigator.userAgent.indexOf('X11') > 0 
) { // linux mozilla
          //alert("linux mozilla / konqueror");
          // DELETE THIS STYLE: #nav li:hover ul
          /*alert (node.style.hover.style.bgColor);
          node.onmouseover=function() {
            this.className+=" over";
          }
          node.onmouseout=function() {
            this.className=this.className.replace(" over", "");
          }
          node.onclick=function() {
            alert("click!");
            document.location.href = 'http://www.drudgereport.com/';
            return false; 
          }*/
        }
      }
    }
  }
 
  //scrollright dom extras
  if (document.getElementById('scrollrightimage')) {
    document.getElementById('scrollrightimage').onclick = scroll_right;
  }
  
}

// could actually load this as soon as nav div is rendered
window.onload=belvoir_init;


function reveal_tab (el) {

  var navtabs = document.getElementById("tabs");
  var nav3 =  document.getElementById("nav3");
  var nav3li = nav3.getElementsByTagName("li");
  var nav3a = nav3.getElementsByTagName("a");
        
  if (document.getElementsByTagName) {
    // handle the tabs
    if (navtabs.children) {
      for (i=0; i < navtabs.children.length; i++) {
        if(navtabs.children[i].nodeName == 'DIV') {
          navtabs.children[i].style.display = 'none';
        }
      }
    }
    else {
      for (i=0; i < navtabs.childNodes.length; i++) {
        if(navtabs.childNodes[i].nodeName == 'DIV') {
          navtabs.childNodes[i].style.display = 'none';
        }
      }
    }
    document.getElementById('tab'+el).style.display ='block';
    // update the nav3 ul list
    for (i=0; i < nav3li.length; i++) {
      if (nav3a[i].href.indexOf(el) > -1) {
        nav3li[i].className = 'sel';
      }
      else {
        nav3li[i].className = '';
      }
    }
    return false;
  }
  else { 
    return true;
  }
  
}


function reveal_image (gallery, el) {

  if (document.getElementById) {
    document.getElementById("gallery").style.backgroundImage = 'url('+gallery+'/'+el+')';
    return false;
  }
  else { 
    return true;
  }
  
}


function scroll_right ( ) {
  window.scrollTo(1000,180);

}


function OpenPopUp(URL, WINDOW, WIDTH, HEIGHT, LEFT, TOP, SCROLLBARS) {
  window.open(URL, WINDOW, 
'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+SCROLLBARS+',resizable=0,width='+WIDTH+',height='+HEIGHT+',top='+TOP+',left='+LEFT);
}   

var b4_calc = 0;

function calcFinalSubscriptionTotals()
{
    if(adult_cost==zero_string||senior_cost==zero_string||concession_cost==zero_string)
    {
        alert('Please select plays for your subscription package before finalising your payment');
        /*var count = 0;
        var cont = true;
        
        while(cont)
        {
            var inp = document.forms['subscription_form'][count];
            count++;
            
            if(inp.name=='selected_production[]')
            {
                inp.focus();
                cont = false;
            }
        }*/
        
        ret = false;
    }
    
    else
    {
        ret = calcSubscriptionTotals();
        
        if(!ret)
            alert('You have not entered enough information. Please select the number of adult, senior or concession packages you wish to subscribe for');
        //else if(ret != grand_total)
            //alert('Your final total is $'+document.forms['subscription_form']['grand_total'].value+'. You will now be redirected to our secure payment server');
    }
        
    return ret;
}

/**
* Javascript function to make sure the user has entered all required credit card payment
* details
*/
function validateCreditCardForm()
{
    error_messages = Array(9);
    /*first get the values from the form*/
    name = document.forms['credit_card_form']['card_name'].value;
    number = document.forms['credit_card_form']['card_number'].value;
    type = document.forms['credit_card_form']['card_type'].value;
    month = document.forms['credit_card_form']['exp_month'].value;
    year = document.forms['credit_card_form']['exp_year'].value;
    var error_occured = false;
    /*now check that the values exist and are valid*/
    if(name=="")
    {
        error_messages[0] = 'Please enter your name as it appears on your credit card';
        error_occured = true;
    }
 
    if(number=="")
    {
        error_messages[1] = 'Please enter your credit card number';
        error_occured = true;
    }

    if(type=="choose")
    {
        error_messages[2] = 'Please choose your card type';
        error_occured = true;
    }

    if(month=="")
    {
        error_messages[3] = 'Please enter the month your card expires';
        error_occured = true;
    }

    if(year=="")
    {
        error_messages[4] = 'Please enter the year your card expires';
        error_occured = true;
    }

    if(!error_occured)
    {
        if(!validateCreditCard(number,type))
        {
            error_messages[5] = 'The credit card you have entered appears not to be valid';
            error_occured = true;
        }

        if(parseInt(month)!=month)
        {
            error_messages[6] = 'Please enter only numbers in the expiry month';
            error_occured = true;
        }

        if(parseInt(year)!=year)
        {
            error_messages[7] = 'Please enter only numbers in the expiry year';
            error_occured = true;
        }

        if(!validateExpiryDate(month,year))
        {
            error_messages[8] = 'Please enter the expiry date in the format mm/yy';
            error_occured = true;
        }

    }

    if(error_occured)
    {
        error_message = 'Please correct the following errors:\n';

        for(i = 0;i<error_messages.length;i++)
        {
            cur_message = error_messages[i];
  
            if(cur_message!=undefined)
                error_message += cur_message+'\n';
        }

        alert(error_message);
        ret = false;
    }

    else
    {
        ret = true;
    }

    return ret;
}

/**
* A functio to make sure that they user has entered a valid month/year combination for the
* expiry date
*/
function validateExpiryDate(month,year)
{
    ret = true;
    date = new Date();
    //check that the length of the year value is 2
    if(year.length!=2)
        ret = false;
    //check that the length of the month value is 2
    if(month.length!=2)
        ret = false;
    //check that the month is from 1 - 12
    if((month<1)||(month>12))
        ret = false;
    //check that the date of expiry is later than now
    if((month<(date.getMonth()+1))&&(parseInt("20"+year)<=date.getYear()))
        ret = false;

    return ret;
}

/**
* A function to check that a credit card entered is valid
* from http://www.evolt.org/article/rating/17/24700/ 
*/
function validateCreditCard(cardNumber,cardType)
{
   var isValid = false;
   var ccCheckRegExp = /[^\d ]/;
   isValid = !ccCheckRegExp.test(cardNumber);

   if (isValid)
   {
     var cardNumbersOnly = cardNumber.replace(/ /g,"");
     var cardNumberLength = cardNumbersOnly.length;
     var lengthIsValid = false;
     var prefixIsValid = false;
     var prefixRegExp;

     switch(cardType)
     {
       case "mastercard":
         lengthIsValid = (cardNumberLength == 16);
         prefixRegExp = /^5[1-5]/;
         break;

       case "visa":
lengthIsValid = (cardNumberLength == 16 || cardNumberLength == 13);
         prefixRegExp = /^4/;
         break;

       case "amex":
         lengthIsValid = (cardNumberLength == 15);
         prefixRegExp = /^3(4|7)/;
         break;

       default:
    return true;
    //     prefixRegExp = /^$/;
    //     alert("Card type not found");
     }

     prefixIsValid = prefixRegExp.test(cardNumbersOnly);
     isValid = prefixIsValid && lengthIsValid;
   }

   if (isValid)
   {
     var numberProduct;
     var numberProductDigitIndex;
     var checkSumTotal = 0;

     for (digitCounter = cardNumberLength - 1;
       digitCounter >= 0;
       digitCounter--)
     {
       checkSumTotal += parseInt (cardNumbersOnly.charAt(digitCounter));
       digitCounter--;
       numberProduct = String((cardNumbersOnly.charAt(digitCounter) * 2));
       for (var productDigitCounter = 0;
         productDigitCounter < numberProduct.length;
         productDigitCounter++)
       {
         checkSumTotal +=
           parseInt(numberProduct.charAt(productDigitCounter));
       }
     }

     isValid = (checkSumTotal % 10 == 0);
   }

   return isValid;
}

/**
* Calculate the subscription totals in the online booking form
*/
function calcSubscriptionTotals()
{
    b4_calc = nanToZero(document.forms['subscription_form']['grand_total'].value);
    if(adult_cost==zero_string||senior_cost==zero_string||concession_cost==zero_string)
    {
        /*alert('Please select plays for your subscription package before finalising your payment');*/
        /*var count = 0;
        var cont = true;
        
        while(cont)
        {
            var inp = document.forms['subscription_form'][count];
            count++;
            
            if(inp.name=='selected_production[]')
            {
                inp.focus();
                cont = false;
            }
        }*/
        
        ret = false;
    }
    
    else
    {
        /*the prices of a book of program tickets*/
        var prog_book_prices = new Array();
        prog_book_prices['choose'] = 0;
        prog_book_prices['book_of_5'] = 25;
        prog_book_prices['book_of_6'] = 30;
        prog_book_prices['book_of_7'] = 35;
        prog_book_prices['book_of_8'] = 40;
        
        /*get the number of adult, senior and concession subscriptions*/                  
        var num_adult = parseInt(document.forms['subscription_form']['num_adult_packages'].value);
        var num_senior = parseInt(document.forms['subscription_form']['num_senior_packages'].value);
        var num_concession = parseInt(document.forms['subscription_form']['num_concession_packages'].value);
        
        num_adult = nanToZero(num_adult);
        num_senior = nanToZero(num_senior);
        num_concession = nanToZero(num_concession);
        adult_cost_local = nanToZero(adult_cost);
        senior_cost_local = nanToZero(senior_cost);
        concession_cost_local = nanToZero(concession_cost);
        
        /*create the package subtotal and set the appropriate field value
        in the form*/
        var packages_subtotal = (num_adult*adult_cost_local) + (num_senior*senior_cost_local) + (num_concession*concession_cost_local);
        document.forms['subscription_form']['packages_subtotal'].value = packages_subtotal;
        /*get the number of program books ordered*/
        var prog_book_qty = parseInt(document.forms['subscription_form']['qty_programme_voucher'].value);
        /*if the field has not been filled in, set the value to 0*/
        prog_book_qty = nanToZero(prog_book_qty);
        /*get the type of book and corresponding cost*/
        var prog_book_type = document.forms['subscription_form']['programme_voucher_type'].value;
        var prog_cost = prog_book_prices[prog_book_type];
        /*calculate the amount and set the value in the appropriate form
        element*/
        var programme_voucher_subtotal = prog_book_qty*prog_cost;
        document.forms['subscription_form']['programme_voucher_subtotal'].value = nanToZero(programme_voucher_subtotal);
        /*get the amount donated*/
        var donation_amount = parseInt(document.forms['subscription_form']['donation_amount'].value);
        donation_amount = nanToZero(donation_amount);
        
        /*check for negative amount in the donations field*/
        if(donation_amount<0)
        {
            ret = false;
            alert('The amount entered in the donations field must be greater than or equal to 0');
        }
        
        else
        {
            /*add all the subtotals and set the value of the appropriate form
            element*/
            var grand_total = packages_subtotal + programme_voucher_subtotal + donation_amount;
            grand_total = nanToZero(grand_total);
            document.forms['subscription_form']['grand_total'].value = grand_total;
        }

        if((grand_total == 0)||(packages_subtotal==0))
        {
            ret = false;
        }
    }
        
    return ret;
}

var package_count     = 0;
var package_min       = 5;
var package_max       = 8;
var zero_string       = 'N/A';
var adult_cost        = zero_string;
var senior_cost       = zero_string;
var concession_cost   = zero_string;
var adult_cost_array = new Array(zero_string,zero_string,zero_string,zero_string,zero_string,227,250,281,312);
var senior_cost_array = new Array(zero_string,zero_string,zero_string,zero_string,zero_string,192,212,238,264);
var concession_cost_array = new Array(zero_string,zero_string,zero_string,zero_string,zero_string,140,154,173,192);
var num_to_string    = new Array(zero_string,zero_string,zero_string,zero_string,zero_string,'FIVE','SIX','SEVEN','EIGHT');

function setPackageCost(btn)
{
    var arg = btn.checked;
    
    if(package_count>=package_max&&arg)
    {
        package_count = package_max;
        alert('The most plays you can subscribe to in one season package is '+package_max);
        btn.checked = false;
    }
        
    else if(package_count<package_max&&arg)
        package_count++;
    
    else if(package_count<=0&&!arg)
    {
        package_count = 0;
        
        for(i = 0;i<document.forms['subscription_form'].length;i++)
        {
            var inp = document.forms['subscription_form'][i];
            
            if(inp.name == 'selected_production[]')
                inp.checked = false;
        }
        
        alert('An error occured, please make your selection again');
    }
    
    else if(package_count>0&&!arg)
        package_count--;

    adult_cost        = adult_cost_array[package_count];
    senior_cost       = senior_cost_array[package_count];
    concession_cost   = concession_cost_array[package_count];
    writeLayer('num_package_shows',num_to_string[package_count]);
    document.forms['subscription_form']['num_package_shows'].value = package_count;
    writeLayer('adult_package_cost',adult_cost);
    writeLayer('senior_package_cost',senior_cost);
    writeLayer('concession_package_cost',concession_cost);
    
    return true;
}

function resetSubscriptionForm()
{
    for(i=0;i<document.forms['subscription_form'].length;i++)
    {
        var inp = document.forms['subscription_form'][i];
        
        if(inp.name=='selected_production[]')
        {
            inp.checked = false;
        }
        
        else if(inp.name!='submit'&&
                inp.name!='first_name'&&
                inp.name!='surname'&&
                inp.name!='address'&&
                inp.name!='postcode'&&
                inp.name!='suburb'&&
                inp.name!='phone_day'&&
                inp.name!='phone_night'&&
                inp.name!='email'&&
                inp.name!='cmp_first_name'&&
                inp.name!='cmp_surname'&&
                inp.name!='cmp_address'&&
                inp.name!='cmp_postcode'&&
                inp.name!='cmp_suburb'&&
                inp.name!='cmp_phone_day'&&
                inp.name!='cmp_phone_night'&&
                inp.name!='cmp_email'&&
                inp.name!='additional_companion_details'&&
                inp.name!='special_assistance'&&
                inp.name!='update_totals'&&
                inp.name!='programme_voucher_type'&&
                inp.name.indexOf('first_date_choice')!=-1&&
                inp.name.indexOf('second_date_choice')!=-1)
            inp.value = '';
    }
}

function layer(layerID)
{/*This function gains access to a CSS object in the document for all browser types*/

    if(document.getElementById)
    {
        return document.getElementById(layerID).style;
    }
    if(document.all)
    {
        return document.all(layerID).style;
    }
    if(document.layers)
    {
        return document.layers[layerID].style;
    }
}

function writeLayer(layerID,txt)
{
    if(document.getElementById)
    {
          document.getElementById(layerID).innerHTML=txt;
    }

    else if(document.all)
    {
          document.all[layerID].innerHTML=txt;
    }

    else if(document.layers)
    {
        with(document.layers[layerID].document)
        {
                open();
                write(txt);
                close();
        }
    }
}

/**
* Check if an argument is not a number
*/
function nanToZero(arg)
{
    arg = parseInt(arg);
    ret = arg;
    argp1 = arg+1;
    arg++;
    
    if(((arg)!=(argp1))||(ret==NaN)||(ret=="NaN"))
        ret = 0;
        
    return ret;
}

/**
* Popup window
*/
function OpenPopUp(URL, WINDOW, WIDTH, HEIGHT, LEFT, TOP, SCROLLBARS)
{
                window.open(URL, WINDOW, 'toolbar=0,location=0,directories=0,status=0,menubar=0,scrollbars='+SCROLLBARS+',resizable=0,width='+WIDTH+',height='+HEIGHT+',top='+TOP+',left='+LEFT);
}   


function competitionPopUp(URL)
{
    day = new Date();
    id = day.getTime();
    eval("page" + id + " = window.open(URL, '" + id + "', 'toolbar=0,scrollbars=1,location=0,statusbar=0,menubar=0,resizable=0,width=580,height=500,left = 680,top = 350');");
}

