
//destination courses dropdown
function changePage(page) {
    if (page != '#') {
        document.getElementById(current).style.display = 'none';
        document.getElementById(page).style.display = 'block';
        current = page;
    }
}

// The following function checks if the user has visited the site before.
// If they have not the welcome text animates into place. Otherwise it stays as
// a small box on the left.

function NewVisitor() {
    jQuery('.bannerWelcomeText').fadeIn("slow");

    jQuery('.bannerWelcome').animate({ height: "238px" }, 1000, function() {
        jQuery('.bannerWelcome').animate({ width: "430px" }, 1000, function() {
            jQuery('.bannerButtonOpen,.bannerButtonClose').toggle();
        })
    });
}

//hide the banner promo box if there are no promos
function noBannerPromos() {
    jQuery('.bannerPromo').toggle();
}

//change language function
function setURL(ctr) {
    var newURL = window.location.href.substring(0, window.location.href.lastIndexOf("/") + 1);
    window.location = newURL + "?mc=" + ctr;
}

function schoolTime(direction,offset){

  var curDateTime = new Date();
  
  var curHour = curDateTime.getHours();
  
  if(direction == "plus") { curHour = curHour + offset; }
      else if(direction == "minus") { curHour = curHour - offset;}
      else { }
      
      var curMin = curDateTime.getMinutes();
      var curSec = curDateTime.getSeconds();
      var curTime = 
        ((curHour < 10) ? "0" : "") + curHour + ":" 
        + ((curMin < 10) ? "0" : "") + curMin + ":" 
        + ((curSec < 10) ? "0" : "") + curSec 
      document.write(curTime);
  }

    var first = true;

    function chooseLanguage(choice){

    //div we are searching through
    var x = document.getElementById('destList').getElementsByTagName('a');
    
    //if it's the first time map is accessed links are stored in name attribute
    //so they can be acccessed again if they are removed (i.e. if the language isnt available)
    if(first)
    {
        for(i=0;i<x.length;i++)
        {
            x[i].name = x[i].href;
        }
    }

    //empty string that gets one of the below strings added onto it depending on the choice parameter.
    var stringToCompare = "";
    
    //locations that should have the NEW image beside them.
    //This should be integrated properly in Sitecore in the future
    var newDestinations = "bristol montreal singapore";

    //declare an individual string for each language
    var english = "bournemouth brighton brighton-campus bristol cambridge cambridge-clare-college hastings london manchester oxford boston chicago honolulu fort-lauderdale los-angeles-redondo-beach miami new-york san-diego san-francisco-mills-college san-francisco-berkeley san-francisco-fishermans-wharf santa-barbara seattle tampa los-angeles-redondo-beach WDC toronto vancouver cape-town brisbane melbourne perth sydney auckland dublin st-julians singapore";
    var french = "nice paris montreal";
    var italian = "rome";
    var german = "munich";
    var chinese = "beijing shanghai";
    var spanish = "barcelona malaga quito costa-rica";
    var dutch = "antwerp"; // is this still being used ?

    //depending on choice parameter add array onto arrayToUse so that we can search through it
    if(choice == "english") stringToCompare += english;
    else if(choice == "french") stringToCompare += french;
    else if(choice == "italian") stringToCompare += italian;
    else if(choice == "german") stringToCompare += german;
    else if(choice == "chinese") stringToCompare += chinese;
    else if(choice == "spanish") stringToCompare += spanish;
    else if(choice == "dutch") stringToCompare += dutch;
    //if all is chosen then concat all strings
    else stringToCompare = english + french + italian + german + chinese + spanish + dutch;
    
    //loop through all links we need to check
    for (i=0;i<x.length;i++)
    {
       
       //trim the link down to just destinations/country/destination...
       var link = new String(x[i].name.substring(x[i].name.indexOf('destinations')+13));
       //trim down to the next slash 
       link = link.substring(link.indexOf('/')+1);
       link = link.replace('/overview/','');
    
       myRE = new RegExp(link, "g");
        
       if(stringToCompare.match(myRE))
       {
            if(newDestinations.match(myRE) && x[i].id.indexOf('country') == -1){
                x[i].className = "newAvailable";
                x[i].setAttribute('href',x[i].name);
            }
            else
            {
                x[i].className = "available";
                x[i].setAttribute('href',x[i].name);
            }
       }
       //if it's a country title
       else if(x[i].id.indexOf('country') != -1)
       {
       
            //declare ctrs so we can remove the flag css from the li element
            var ctrs = new Array("uk","us","ca","sa","au","nz","ir","mt","fr","de","it","es","ec","cr","cn","nl","be","sg");
            
            for(k=0;k<ctrs.length;k++)
            {
                if(document.getElementById("ctr_"+ctrs[k])) //if the element exists
                {
                    var y = document.getElementById("ctr_"+ctrs[k]).getElementsByTagName('li')
                    //only leave the title css
                    y[0].className = "destTitle";
                }
            }
            
            //so we can use it again below.
            ctrs = null;
            
            x[i].className = "unavailable";
            x[i].removeAttribute('href');
            
            switch(choice)
            {
                case "all":
                    var ctrs = new Array("uk","us","ca","sa","au","nz","ir","mt","fr","de","it","es","ec","cr","cn","nl","be","sg");
                    var ctrNames = new Array("united-kingdom","united-states","canada","south-africa","australia","new-zealand","ireland","malta","france","germany","italy","spain","ecuador","costa-rica","china","netherlands","belgium","singapore");
                break;
                case "english":
                    //singapore offers english and chinese
                    var ctrs = new Array("uk","us","ca","sa","au","nz","ir","mt","sg");
                    var ctrNames = new Array("united-kingdom","united-states","canada","south-africa","australia","new-zealand","ireland","malta","singapore");
                break;
                case "french":
                    //Montreal offers french
                    var ctrs = new Array("fr","ca");
                    var ctrNames = new Array("france","canada");
                break;
                case "german":
                    var ctrs = new Array("de");
                    var ctrNames = new Array("germany");
                break;
                case "spanish":
                    var ctrs = new Array("es","ec","cr");
                    var ctrNames = new Array("spain","ecuador","costa-rica");
                break;
                case "italian":
                    var ctrs = new Array("it");
                    var ctrNames = new Array("italy");
                break;
                case "chinese":
                    var ctrs = new Array("cn","sg");
                    var ctrNames = new Array("china","singapore");
                break;
                case "dutch":
                    var ctrs = new Array("nl","be");
                    var ctrNames = new Array("netherlands","belgium");
                break;
                default:
                    //same as all
                    var ctrs = new Array("uk","us","ca","sa","au","nz","ir","mt","fr","de","it","es","ec","cr","cn","nl","be","sg");
                    var ctrNames = new Array("united-kingdom","united-states","canada","south-africa","australia","new-zealand","ireland","malta","france","germany","italy","spain","ecuador","costa-rica","china","netherlands","belgium","singapore");
                break;
            }
            
            for(j=0;j<ctrs.length;j++)
            {
                if(document.getElementById('ctr_'+ctrs[j]))
                {
                    var title = document.getElementById('ctr_'+ctrs[j]).getElementsByTagName('a');
                    title[0].setAttribute('href','/master/ils/destinations/'+ctrNames[j]);
                    title[0].className = "available";
                }
                if(document.getElementById('ctr_'+ctrs[j]))
                {
                    var y = document.getElementById('ctr_'+ctrs[j]).getElementsByTagName('li');
                    //this is doing some weird loop, need to fix
                    y[0].className = "destTitle flag_"+ctrs[j];
                }

                title = null;y = null;               
            }
            
       }
       else
       {
            if(newDestinations.match(myRE)){
                x[i].className = "newUnavailable";
            }
            else
            {
                x[i].className = "unavailable"; 
            }
            
            x[i].removeAttribute('href');
       }
       
    }
    
    first = false;
    
    //set active css on language
    var links = jQuery('.langChoice a');
    
    //set all links to have empty class, except for choice variable that's passed into function
    for(i=0;i<links.length;i++)
    {
        if(links[i].id != choice)
        {
            links[i].className = "";
        }
        else
        {
            links[i].className = "active";
        }
    }
    
    //blur the clicked link
    document.getElementById(choice).blur();
}

/* centered popup window */
function centerPopup(url, default_left, default_top, width, height, scrollbars, winName) {
    var posX, posY;

    posX = default_left;
    posY = default_top;

    if (parseFloat(navigator.appVersion) >= 4.0) {
    posX = parseInt(screen.availWidth / 2.0) - (width / 2.0);
    posY = parseInt(screen.availHeight / 2.0) - (height / 2.0);
    }

    if (scrollbars) {
    var win = window.open(url, (winName == null ? "popupWin" : winName), "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=1,location=no,status=yes,left=" + posX + ",top=" + posY);
    } else {
    var win = window.open(url, (winName == null ? "popupWin" : winName), "width=" + width + ",height=" + height + ",resizable=yes,scrollbars=0,left=" + posX + ",top=" + posY);
    }

    if (parseFloat(navigator.appVersion) >= 4.0) {
    win.moveTo(posX, posY);
    if (navigator.appName.indexOf("Netscape") != -1)
    win.focus();
    }
}

function toggleThis(obj) {
    var theBox = obj.parentNode.getElementsByTagName("ul")[0];
    if (theBox.style.display == 'block') theBox.style.display = 'none'
    else {
        var objs = obj.parentNode.parentNode.getElementsByTagName("ul")
        for (i = 0; i < objs.length; i++) {
            objs[i].style.display = 'none'
        }
        theBox.style.display = 'block'
    }
}

/* RESERVATION FUNCTIONS */

function SetUniqueRadioButton(nameregex, current, price) {
    //this is to check if is the first time
    if (jQuery(".AccomSelected").val() == "") {
        CalculateTotal(current, price);
        return;
    }

    var hasChanged = false;

    re = new RegExp(nameregex);
    for (i = 0; i < document.forms[0].elements.length; i++) {
        elm = document.forms[0].elements[i]
        if (elm.type == 'radio') {
            if (re.test(elm.name) && elm.id != current.id) {
                if (elm.checked) {
                    hasChanged = true;
                    elm.checked = false;
                    CalculateTotal(elm, elm.value);
                    break;
                }

            }
        }
    }

    //calculate only when another option is unclick
    if (hasChanged) {
        CalculateTotal(current, price);
    }
}

//Does the calculation when selecting different items.
function CalculateTotal(current, price) {
    //find the values by Class
    var totalPriceTD = jQuery(".totalPriceTD");
    var travelServicesPrice = Number(jQuery(".priceTravelServices").html());
    var travelServicesTD = jQuery(".priceTravelServices");
    var totalPrice = Number(jQuery(".totalPriceTD").html());

    if (current.checked) {
        totalPrice += Number(price);
        travelServicesPrice += Number(price);
    }
    else {
        totalPrice -= Number(price);
        travelServicesPrice -= Number(price);
    }
    totalPriceTD.text(totalPrice);
    travelServicesTD.text(travelServicesPrice);

    //need to save them again in a hidden field.
    var totalTravelServicesHD = jQuery(".totalTravelServicesHD");
    var totalPriceHD = jQuery(".totalPriceHD");
    totalTravelServicesHD.val(travelServicesPrice);
    totalPriceHD.val(totalPrice);

    //saves the selected value in a hidden field    
    var el = jQuery('input:checkbox:checked');
    var newExtra = "";
    for (var i = 0; i < el.length; i++) {
        if (el.length == 1 || el.length == i + 1)
            var concatenator = '';
        else
            var concatenator = '|';
        newExtra += el[i].id.split('|')[1] + concatenator;
    }
    jQuery(".BExtrasSelected").val(newExtra);
    var elAccom = jQuery('input:radio:checked');
    if (elAccom.attr("id") != undefined)
        jQuery(".AccomSelected").val(elAccom.attr("id").split('|')[1]);
}
//validate the form before submiting
function ValidateForm() {
    if (jQuery(".AccomSelected").val() == "") {
        alert(jQuery(".errAccomMissingClass").val());
        return false;
    }
}
//show and hide 'For more information' div
function expandcollapse2(thisClass) {
    var el = jQuery("." + thisClass);
    if (el.css('display') == 'none')
        el.show();
    else
        el.hide();

    return false;
}

function validateNewsletterSignup(fname, lname, email) {

    var errors = new Boolean();
    errors = false;

    //first name
    if (!jQuery('#' + fname).val()) {
        errors = true;
        jQuery('#fnameTD').addClass("error");
    }
    else {
        jQuery('#fnameTD').removeClass("error")
    };

    //last name
    if (!jQuery('#' + lname).val()) {
        errors = true;
        jQuery('#lnameTD').addClass("error");
    }
    else {
        jQuery('#lnameTD').removeClass("error")
    };

    //email
    if (!checkValidEmail(jQuery('#' + email).val())) {
        errors = true;
        jQuery('#emailTD').addClass("error");
    }
    else {
        jQuery('#emailTD').removeClass("error")
    };

    return !errors;
}

function checkValidEmail(object) {
    var emailReg = /^[a-zA-Z0-9._-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,4}$/;
    var regex = new RegExp(emailReg);
    return regex.test(object);
}

function changeAgent(form) {
    if (document.getElementsByTagName) {
        var ULElement = document.getElementsByTagName("li");
        for (var i = 0; i < ULElement.length; i++) {
            var tag = ULElement[i];

            if (tag.className == "agentselected") {
                tag.className = "agenthidden";
            }
        }

        var ele = document.getElementById(String(form.value));
        ele.className = "agentselected";
    }
}