var excDetails;
var excTitles;
var basketForms;
var selects;
var xmlhttp;
var cruisespast;
var cruisesbooked;

/*---------------------------------------
INITIALISE EXCURSIONS PAGE 
- initExcursions()
- initExcOpenClose()
- initExcBasket()
- excursionsReset();
---------------------------------------*/
function initExcursions() {
    // get a nodelist of all excursion details containers
    excDetails = document.getElementsByTagName('DD');

    // get a nodelist of all excursion title containers
    excTitles = document.getElementsByTagName('DT');

    // get a nodelist of all excursion basket forms
    basketForms = document.getElementById('excursions').getElementsByTagName('FORM');

    // get a nodelist of all select elements
    selects = document.getElementsByTagName('SELECT');

    // initialise the open/close mechanism on excursion details
    initExcOpenClose();

    // initialise the basket pop-up mechanism
    initExcBasket();
}

function initExcOpenClose() {
    var i;

    // for each excursion details container...
    for (i = 0; i < excDetails.length; i++) {
        // close the container
        changeClass('closed', excDetails, i);
    }

    // for each excursion title container...
    for (i = 0; i < excTitles.length; i++) {
        // close the container
        changeClass('closed', excTitles, i);

        // create 'open' links for each excursion
        var openLink = document.createElement('A');
        openLink.setAttribute('index', i); // custom attribute to identify the links individually
        openLink.setAttribute('href', '#');
        openLink.innerHTML = 'Open';
        openLink.title = 'Open';

        // apply events to the 'open' links to be triggered on click and keypress
        openLink.onclick = function() {
            return false; // prevents link being followed
        }
        openLink.onkeypress = function() {
            return false; // prevents link being followed
        }

        // insert them into the title container (as the first child)
        var firstChild = excTitles[i].firstChild;
        excTitles[i].insertBefore(openLink, firstChild);

        // apply events to the exursion title container triggering a click of the 'open' link
        // if a click is registered anywhere inside it.
        excTitles[i].onclick = function() {
            var links = this.getElementsByTagName('A');
            toggleExcOpenClose(links[0]);
        }
    }
}

function initExcBasket() {
    var i;
    var j;
    var links;
    var link;
    var addToBasketIndex = 0;

    // create a 'pagemask' div element for use when basket forms are visible
    var pageMask = document.createElement('DIV');
    pageMask.id = 'pagemask';
    pageMask.style.opacity = .5;
    pageMask.style.filter = 'alpha(opacity=50)';

    // insert it into the body (as the last child)
    document.body.appendChild(pageMask);

    // reset the excursions page to its original display settings
    excursionsReset();

    // apply submit events to basket forms
    applyBasketFormsSubmitEvents();

    // for each excursion details container...
    for (i = 0; i < excDetails.length; i++) {
        // get a nodelist of all links in the container
        links = excDetails[i].getElementsByTagName('A');

        // for each link...
        for (j = 0; j < links.length; j++) {
            link = links[j];
            if (link.className == 'imgbut addtobasket') {

                // display the link if its an 'add to basket' link
                link.style.display = 'inline-block';

                // add a custom attribute to identify the links individually
                link.setAttribute('index', addToBasketIndex);
                addToBasketIndex++;

                // apply events to the 'add to basket' links to be triggered on click and keypress
                link.onclick = function() {
                    showBasketForm(this);
                    return false; // prevents link being followed
                }
                link.onkeypress = function() {
                    if (event.keyCode == 13) { // enter key pressed
                        showBasketForm(this);
                    }
                    return false; // prevents link being followed
                }
            }
            else if (link.className == 'imgbut cancel') {

                // display the link if its a 'cancel' link
                link.style.display = 'inline-block';

                // apply events to the 'cancel' links to be triggered on click and keypress
                link.onclick = function() {
                    hideAllBasketForms();
                    return false; // prevents link being followed
                }
                link.onkeypress = function() {
                    if (event.keyCode == 13) { // enter key pressed
                        hideAllBasketForms();
                    }
                    return false; // prevents link being followed
                }
            }
        }
    }
}

function excursionsReset() {
    var i;
    var basketForm;

    // hide all the basket forms
    hideAllBasketForms();

    // for each basket form...
    for (i = 0; i < basketForms.length; i++) {
        // set the correct display for the form's contents
        basketForm = basketForms[i];
        basketForm.children[0].style.display = 'block';
        basketForm.children[1].style.display = 'none';
        basketForm.children[1].innerHTML = "";
    }
}

/*---------------------------------------
INITIALISE MY CRUISES PAGE
- initMyCruises()
---------------------------------------*/
function initMyCruises() {
    // get a nodelist of all excursion details containers
    excDetails = document.getElementsByTagName('DD');

    // get a nodelist of all excursion title containers
    excTitles = document.getElementsByTagName('DT');

    // initialise the open/close mechanism on excursion details
    initExcOpenClose();

    // get the booked and past cruises DIVs
    cruisesbooked = document.getElementById('mycruises-booked');
    cruisespast = document.getElementById('mycruises-past');

    // hide the 'mycruises-past' DIV 
    cruisespast.style.display = 'none';

    // attach events to the 'mycruises-menu'
    var cruisesmenu = document.getElementById('mycruises-menu');
    var cruisesmenuLIs = cruisesmenu.getElementsByTagName('LI');
    var cruisesmenulinks = cruisesmenu.getElementsByTagName('A');

    // if first link is clicked (booked cruises)
    cruisesmenulinks[0].onclick = function() {
        toggleMyCruisesDisplay(cruisesmenuLIs, 'booked');
        return false; // prevents link being followed
    }
    cruisesmenulinks[0].onkeypress = function() {
        if (event.keyCode == 13) { // enter key pressed
            toggleMyCruisesDisplay(cruisesmenuLIs, 'booked');
        }
        return false; // prevents link being followed
    }

    // if second link is clicked (past cruises)
    cruisesmenulinks[1].onclick = function() {
        toggleMyCruisesDisplay(cruisesmenuLIs, 'past');
        return false; // prevents link being followed
    }
    cruisesmenulinks[1].onkeypress = function() {
        if (event.keyCode == 13) { // enter key pressed
            toggleMyCruisesDisplay(cruisesmenuLIs, 'past');
        }
        return false; // prevents link being followed
    }

    // if third link is clicked (all cruises)
    cruisesmenulinks[2].onclick = function() {
        toggleMyCruisesDisplay(cruisesmenuLIs, 'all');
        return false; // prevents link being followed
    }
    cruisesmenulinks[2].onkeypress = function() {
        if (event.keyCode == 13) { // enter key pressed
            toggleMyCruisesDisplay(cruisesmenuLIs, 'all');
        }
        return false; // prevents link being followed
    }

}

/*---------------------------------------
INITIALISE BASKET PAGE
- initBasket()
---------------------------------------*/
function initBasket() {
    // Get the expanded basket
    var basket = document.getElementById('basket-expanded');

    // get a nodelist of all excursion basket forms
    basketForms = basket.getElementsByTagName('FORM');

    // get a nodelist of all select elements
    selects = document.getElementsByTagName('SELECT');

    // create a 'pagemask' div element for use when basket forms are visible
    var pageMask = document.createElement('DIV');
    pageMask.id = 'pagemask';
    pageMask.style.opacity = .5;
    pageMask.style.filter = 'alpha(opacity=50)';

    // insert it into the body (as the last child)
    document.body.appendChild(pageMask);

    // reset the excursions page to its original display settings
    excursionsReset();

    // apply submit events to basket forms
    applyBasketFormsSubmitEvents();

    // get a nodelist of all links in the expanded basket 
    var links = basket.getElementsByTagName('A');

    // for each link...
    var i;
    var link;
    var addToBasketIndex = 0;
    for (i = 0; i < links.length; i++) {
        link = links[i];
        if (link.className == 'imgbut editpassengers') {

            // display the link if its an 'edit passengers' link
            link.style.display = 'inline-block';

            // add a custom attribute to identify the links individually
            link.setAttribute('index', addToBasketIndex);
            addToBasketIndex++;

            // apply events to the 'add to basket' links to be triggered on click and keypress
            link.onclick = function() {
                showBasketForm(this);
                return false; // prevents link being followed
            }
            link.onkeypress = function() {
                if (event.keyCode == 13) { // enter key pressed
                    showBasketForm(this);
                }
                return false; // prevents link being followed
            }
        }
        else if (link.className == 'imgbut cancel') {

            // display the link if its a 'cancel' link
            link.style.display = 'inline-block';

            // apply events to the 'cancel' links to be triggered on click and keypress
            link.onclick = function() {
                hideAllBasketForms();
                return false; // prevents link being followed
            }
            link.onkeypress = function() {
                if (event.keyCode == 13) { // enter key pressed
                    hideAllBasketForms();
                }
                return false; // prevents link being followed
            }
        }
    }
}

/*---------------------------------------
SHOW/HIDE CRUISES
- toggleMyCruisesDisplay(cruisesmenuLIs, mode)
---------------------------------------*/
function toggleMyCruisesDisplay(cruisesmenuLIs, mode) {

    // for each LI...
    var i = 0;
    for (i = 0; i < cruisesmenuLIs.length; i++) {
        // Remove any 'selected' class
        changeClass('', cruisesmenuLIs, i);
    }

    switch (mode) {
        case 'booked':
            {
                // show booked, hide past
                cruisesbooked.style.display = 'block';
                cruisespast.style.display = 'none';
                // add selected class to the right LI
                changeClass('selected', cruisesmenuLIs, 0);
            }
            break;
        case 'past':
            {
                // hide booked, show past
                cruisesbooked.style.display = 'none';
                cruisespast.style.display = 'block';
                // add selected class to the right LI
                changeClass('selected', cruisesmenuLIs, 1);
            }
            break;
        case 'all':
            {
                // show booked, show past
                cruisesbooked.style.display = 'block';
                cruisespast.style.display = 'block';
                // add selected class to the right LI
                changeClass('selected', cruisesmenuLIs, 2);
            }
            break;
    }
}

/*---------------------------------------
OPEN/CLOSE EXCURSIONS
- toggleExcOpenClose(elem)
- function changeClass(newClass, nodeList, index)
---------------------------------------*/
function toggleExcOpenClose(elem) {
    if (elem.firstChild.data == 'Open') {
        // link is currently 'open', set to 'close'
        elem.innerHTML = 'Close';
        elem.title = 'Close';

        // open the correct excursion details container, based on link's index attribute
        changeClass('opened', excDetails, elem.getAttribute('index'));

        // open the correct excursion titles container, based on link's index attribute
        changeClass('opened', excTitles, elem.getAttribute('index'));
    }
    else { // elem.firstChild.data == 'Close'
        // link is currently 'close', set to 'open'
        elem.innerHTML = 'Open'
        elem.title = 'Open';

        // close the correct excursion details container, based to link's index attribute
        changeClass('closed', excDetails, elem.getAttribute('index'));

        // close the correct excursion titles container, based to link's index attribute
        changeClass('closed', excTitles, elem.getAttribute('index'));
    }
}

function changeClass(newClass, nodeList, index) {
    // change the class of the node at the provided index
    nodeList[index].className = newClass;
}

/*---------------------------------------
FORM SUBMIT EVENTS AND VALIDATION
- applyBasketFormsSubmitEvents()
---------------------------------------*/
function applyBasketFormsSubmitEvents() {
    var i;

    // for each basket form...
    for (i = 0; i < basketForms.length; i++) {
        // apply a submit event
        basketForms[i].onsubmit = function() {
            return validateBasketFormsSubmit(this);
        }
    }
}

function validateBasketFormsSubmit(form) {
    var checkFound = false;
    var j;

    // Check to see if at least one passenger has been selected
    // Actually just checking that at least one checkbox in this form is checked, so if
    // form structure changes, adding checkboxes for other purposes, this may not be good enough
    for (j = 0; j < form.length; j++) {
        if ((form.elements[j].type == "checkbox") && (form.elements[j].checked == true)) {
            checkFound = true;
        }
    }
    if (!checkFound) {
        alert("Please select at least one passenger");
        return false; // prevents submission happening
    }
    else {
        if (form.action.indexOf("/my-cruises/my-cruise-account/basketconfirm") != -1)
            submitMyForm(form, form.action);
        else
            form.submit();
        //submitMyForm(form, "/mw-html/basket-form-response.html");
        return false; // prevents HTML (non-JavaScript) submission happening
    }
}
function submitMyForm(form, url) {
    var excursionid = form.name.substring(5, form.name.length);
    var params = "excursionID=" + excursionid;
    for (j = 0; j < form.length; j++) {
        if ((form.elements[j].type == "checkbox")) {
            var val = "";
            if (form.elements[j].checked == true)
                val = "on";
            params += "&passengers=" + val;
        }
    }
    $("#progressBar").html("<img src='images/wait.gif' alt='Please wait...' style='margin-left:50px; />");
    $.ajax({
        type: "POST",
        url: url,
        data: params,
        success: function(msg) {
            if (msg == "NotSameCruise") {
                alert("the excursion can't be added to basket, please  make the payment for excursions already in the basket first.");
            }
            else if (msg == "Sessiontimeout") {
                window.parent.location.reload();
            }
            else {
                // hide the fieldset the basket form
                form.children[0].style.display = 'none';
                // show the confirmation DIV and update its innerHTML with the response
                form.children[1].style.display = 'block';
                form.children[1].innerHTML = msg;

                // get a nodelist of all links in the confirmation DIV 
                var links = form.children[1].getElementsByTagName('A');

                // for each link...
                var i;
                var link;
                for (i = 0; i < links.length; i++) {
                    link = links[i];
                    if (link.className == 'imgbut continuetobrowse') {

                        // apply events to the 'cancel' links to be triggered on click and keypress
                        link.onclick = function() {
                            excursionsReset();
                            return true; // prevents link being followed
                        }
                        link.onkeypress = function() {
                            if (event.keyCode == 13) { // enter key pressed
                                excursionsReset();
                            }
                            return false; // prevents link being followed
                        }
                    }
                }
            }
        }
    });

}
function loadXMLDoc(form, url) {
    if (window.XMLHttpRequest) {
        // for IE7+, Firefox, Chrome, Opera, Safari
        xmlhttp = new XMLHttpRequest();
    }
    else {
        // for IE6, IE5
        xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
    }
    xmlhttp.onreadystatechange = function() {
        stateChanged(form);
    };
    var excursionid = form.name.substring(5, form.name.length);
    var params = "excursionID=" + excursionid;
    for (j = 0; j < form.length; j++) {
        if ((form.elements[j].type == "checkbox")) {
            var val = "";
            if (form.elements[j].checked == true)
                val = "on";
            params += "&passengers=" + val;
        }
    }
    xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    xmlhttp.setRequestHeader("Content-length", params.length);
    xmlhttp.setRequestHeader("Connection", "close");
    xmlhttp.open("GET", url, true);
    xmlhttp.send(params);
}

function stateChanged(form) {
    alert(1);
    if (xmlhttp.readyState == 4) { // ready
        alert(2);
        if (xmlhttp.status == 200) { // OK
            // hide the fieldset the basket form
            form.children[0].style.display = 'none';
            // show the confirmation DIV and update its innerHTML with the response
            form.children[1].style.display = 'block';
            form.children[1].innerHTML = xmlhttp.responseText;

            // get a nodelist of all links in the confirmation DIV 
            var links = form.children[1].getElementsByTagName('A');

            // for each link...
            var i;
            var link;
            for (i = 0; i < links.length; i++) {
                link = links[i];
                if (link.className == 'imgbut continuetobrowse') {

                    // apply events to the 'cancel' links to be triggered on click and keypress
                    link.onclick = function() {
                        excursionsReset();
                        return false; // prevents link being followed
                    }
                    link.onkeypress = function() {
                        if (event.keyCode == 13) { // enter key pressed
                            excursionsReset();
                        }
                        return false; // prevents link being followed
                    }
                }
            }
        }
        else {
            alert("There was a problem in the returned data");
        }
    }
}

/*---------------------------------------
SHOW/HIDE BASKET FORMS
- showBasketForm(elem)
- hideAllBasketForms()
- maskPage()
- unmaskPage()
- centerElement(elem)
---------------------------------------*/
function showBasketForm(elem) {
    // mask the page
    maskPage();

    // open the correct excursion basket form, based on link's index attribute
    changeClass('showing', basketForms, elem.getAttribute('index'));

    // position the basket form roughly center of the browser window
    centerElement(basketForms[elem.getAttribute('index')]);
}

function hideAllBasketForms() {
    var i;

    // unmask the page
    unmaskPage();

    // for each excursion basket form...
    for (i = 0; i < basketForms.length; i++) {
        // hide the form
        changeClass('hidden', basketForms, i)
    }
}

function maskPage() {
    var i = 0;

    // get the mask's dimensions
    var maskDimensions = getMaskDimensions();

    // mask the page
    var pageMask = document.getElementById('pagemask');
    pageMask.style.width = maskDimensions.width + 'px';
    pageMask.style.height = maskDimensions.height + 'px';
    pageMask.style.display = 'block';

    // for each select...
    for (i = 0; i < selects.length; i++) {
        // hide the select (affects all browsers,
        // but used for IE6, as selects always sit over the mask otherwise)
        selects[i].style.visibility = 'hidden';
    }
}

function unmaskPage() {
    var i = 0;

    // re-enable the page
    var pageMask = document.getElementById('pagemask');
    pageMask.style.display = 'none';

    // for each select...
    for (i = 0; i < selects.length; i++) {
        // show the select
        selects[i].style.visibility = 'visible';
    }
}

function centerElement(elem) {
    // get the viewport's dimensions
    var viewportDimensions = getViewportDimensions();

    // determine the center placement of the element in the viewport, according to the dimensions of both, 
    // defaulting to left = 50, top = 50 if viewport dimensions = 0
    var left = (viewportDimensions.width == 0) ? 50 : parseInt((viewportDimensions.width - elem.offsetWidth) / 2, 10);
    var top = (viewportDimensions.height == 0) ? 50 : parseInt((viewportDimensions.height - elem.offsetHeight) / 2, 10);

    // get the scroll offset
    var scrollOffset = getScrollOffset();

    // position the element, including the scroll offset
    elem.style.left = left + scrollOffset.width + 'px';
    elem.style.top = top + scrollOffset.height + 'px';
}

/*---------------------------------------
CALCULATION OF DIMENSIONS, all return width/height
- getMaskDimensions()
- getDocDimensions()
- getViewportDimensions()
- getScrollOffset()
---------------------------------------*/
function getMaskDimensions() {
    var w = 0;
    var h = 0;

    // get the page and viewport dimensions
    var docDimensions = getDocDimensions();
    var viewportDimensions = getViewportDimensions();

    // set the width and height to the document dimensions
    w = docDimensions.width;
    h = docDimensions.height;

    // update the width and height to use the viewport dimensions, if greater
    if (w < viewportDimensions.width) {
        w = viewportDimensions.width;
    }
    if (h < viewportDimensions.height) {
        h = viewportDimensions.height;
    }

    // return the width and height
    return {
        width: w,
        height: h
    };
}

function getDocDimensions() {
    var w = 0;
    var h = 0;

    if (document.documentElement.scrollWidth) {
        // assuming document.documentElement.scrollHeight is also available
        w = document.documentElement.scrollWidth;
        h = document.documentElement.scrollHeight;
    }

    // return the width and height
    return {
        width: w,
        height: h
    };
}

function getViewportDimensions() {
    var w = 0;
    var h = 0;

    if (document.documentElement.clientWidth) {
        // assuming document.documentElement.clientHeight is also available
        w = document.documentElement.clientWidth;
        h = document.documentElement.clientHeight;
    }

    // return the width and height
    return {
        width: w,
        height: h
    };
}

function getScrollOffset() {
    var w = 0;
    var h = 0;

    if (window.pageXOffset || window.pageYOffset) {
        w = window.pageXOffset;
        h = window.pageYOffset;
    }
    else if (document.documentElement.scrollLeft || document.documentElement.scrollTop) {
        w = document.documentElement.scrollLeft;
        h = document.documentElement.scrollTop;
    }

    // return the width and height
    return {
        width: w,
        height: h
    };
}

/*---------------------------------------
INITIALISE REGISTER PAGE
- initMyRegister()
---------------------------------------*/
function initMyRegister() {
    // create a 'pagemask' div element for use when basket forms are visible
    var pageMask = document.createElement('DIV');
    pageMask.id = 'pagemask';
    pageMask.style.opacity = .5;
    pageMask.style.filter = 'alpha(opacity=50)';

    // insert it into the body (as the last child)
    document.body.appendChild(pageMask);

    // get a nodelist of all select elements
    selects = document.getElementsByTagName('SELECT');
}

