
// nsb-clock.js
if (navigator.appName == "Microsoft Internet Explorer")	{
    document.attachEvent("onreadystatechange", function () {
        window.setTimeout('CoolClock.findAndCreateClocks()', 100);
    });
} else   {
    jQuery(document).ready(function($) {
        CoolClock.findAndCreateClocks();
    });
}

// nsb-booking.js
jQuery(document).ready(function($) {

    // BOOKING
    booking_init();

    season_booking_init();

    // initializes season booking
    function season_booking_init() {
        // initialize autocomplete
        var travel = $("#seasonticket_trip_form-from_station, #seasonticket_trip_form-to_station").autocomplete({
            source: function( request, response ) {
                var matcher = new RegExp("^"+request.term, "i");
                var ret=new Array();
                for (number in allseasonstations) {
                    var station=allseasonstations[number];
                    if (matcher.test(station.label)) {
                        var found=false;
                        for (i in ret) {
                            var el = ret[i];
                            if (station.value == el) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            ret.push( station.value );
                        }
                    }
                }
                response(ret);
            }
        });
    }


    // initializes region booking
    function booking_init() {
        // initialize autocomplete
        var travel = $("#booking-from, #booking-to, #ontime-from, #ontime-to, input.station").autocomplete({
            source: function( request, response ) {
                var matcher = new RegExp("^"+request.term, "i");
                var ret=new Array();
                for (number in allstations) {
                    var station=allstations[number];
                    if (matcher.test(station.label)) {
                        var found=false;
                        for (i in ret) {
                            var el = ret[i];
                            if (station.value == el) {
                                found = true;
                                break;
                            }
                        }
                        if (!found) {
                            ret.push( station.value );
                        }
                    }
                }
                response(ret);
            }
        });

        // passengers was changed
        $('#booking-passengers').change(function() {
            var passengers = $(this).val();
            
            if (passengers == 10) {
                window.location = grouptravellink;
            } else {
                booking_update_passengers(passengers);
            }
        });


        // SINGLE OR RETURN
        // Return
        $('#booking input[type=radio].return').change(function() {
            if (this.checked) {
                $('#booking-when .return').show();
            }
        });
        
        // Single
        $('#booking input[type=radio].single').change(function() {
            if (this.checked) {
                $('#booking-when .return').hide();
            }
        });
    }
    
    // update passengers
    function booking_update_passengers(passengers) {
        for (i = 1; i <= 9; i++) {
            if (i <= passengers) {
                $('#booking-passenger-'+i+'').show();
            } else {
                $('#booking-passenger-'+i+'').hide();
            }
        }
        
    }
    
    // booking overlay
    $("#booking").submit(function() { 
        $("#booking-overlay").dialog({
            width: 300,
            height: 300,
            modal: true
        });

        passengers = $('#booking-passengers').val();
        
        // show waiting dialog if 2 passengers	
        return true;
    });
});

// nsb-checkout-journey.js
jQuery(document).ready(function($) {
    
    // JOURNEY
    journey_init();
    
    // initialize journey selection
    function journey_init() {
        // show/hide details
        $("#journey-outward tbody td.route a, #journey-return tbody td.route a, #timetable tbody td.route a,  table.journey tbody td.route a, #journey-outward tbody td.duration a, #journey-return tbody td.duration a, table.journey tbody td.duration a").click(function() {
            var row = $(this).parents('tr'); // Goto first table row found
            var cl = row.attr('class');
            var rowId = cl.substr(cl.indexOf('row'), 5);
            var journey_details  = $(this).parents('.journey tbody').children('tr[class*="'+rowId+'"][class*="details"]');
            var journey_option   = $(this).parents('.journey tbody').children('tr[class*="'+rowId+'"][class*="option"]');
            var journey_sections = $(this).parents('.journey tbody').children('tr[class*="'+rowId+'"][class*="section"]');

            journey_sections.toggle();
            journey_details.show();		
            if (journey_sections.is(':visible'))	{
                journey_option.addClass('open');
                journey_details.addClass('open');
            }
            else	{
                journey_option.removeClass('open');
                journey_details.removeClass('open');
            }
            return false;
        });

        // show/hide message details
        $("#timetable .message a.showmore").click(function() {
            var message_details = $(this).parent().parent().find('span');
            var message_more = $(this).parent().parent().find('em');
            message_details.toggle();
            message_more.toggle();			
            return false;
        });
        
        $("#journey-outward .message a.showmore, #journey-return .message a.showmore").click(function() {
            var message_details = $(this).parent().find('span');
            var message_more = $(this).parent().find('em');
            message_details.toggle();
            message_more.toggle();          
            return false;
        });
        
    }
});

// nsb-checkout-service.js
jQuery(document).ready(function($) {
    
    // SERVICE
    service_init();
    
    // initialize journey selection
    function service_init() {
        // journey selection
        $("#service-return input, #service-departure input").click(function() {
            // get journey and sections
            var stages           = $(this).parents('#checkout').find('table.service');
            var section          = $(this).parents('tbody');
            var section_cell     = $(this).parents('td');
            var section_option   = $(this).parents('tr');
            var section_features = $(section_option).find('td.features a span.open');
            var section_close    = $(section_option).find('td.features a span.close');
            var section_details  = $(section_option).next('tr.details');
            var section_previous = $($(section_option).prevAll('tr.option')[0]);
            var section_previous = $(section_option).prev('tr.option');
            
            // remove classes
            section.find('tr').removeClass('selected');
            section.find('td').removeClass('on');
            stages.find('tr').removeClass('open');
            stages.find('.prev-row').removeClass('prev-row');
            stages.find('.extra_selection').removeClass('show');
            
            // hide details
            stages.find('tr.details').hide();
            stages.find('td.features a span.open').show();
            stages.find('td.features a span.close').hide();
            
            // add class
            section_cell.addClass('on');
            section_option.addClass('selected');
            section_details.addClass('selected');
            
            // show details
            if (section_details.html()) {
                section_option.addClass('open');
                section_option.find('.extra_selection').addClass('show');
                section_previous.addClass('prev-row');
                section_features.hide();
                section_close.show();
                section_details.show('fast');
            }
            
        });

        // show/hide details
        $("#service-departure .features a, #service-return .features a, ").click(function() {
            var stages           = $(this).parents('#checkout').find('table.service');
            var section          = $(this).parents('tbody');
            var section_cell     = $(this).parents('td');
            var section_option   = $(this).parents('tr');
            var section_features = $(section_option).find('td.features a span.open');
            var section_close    = $(section_option).find('td.features a span.close');
            var section_details  = $(section_option).next('tr.details');
            
            var isOpen = $(section_details).is(":visible");

            if (isOpen){
                section_option.removeClass('open');
                section_details.hide();
                section_features.show();
                section_close.hide();
                stages.find('.extra_selection').removeClass('show');
            } else {
                stages.find('tr').removeClass('open');
                stages.find('tr.details').hide();
                stages.find('td.features a span.open').show();
                stages.find('td.features a span.close').hide();

                section_option.addClass('open');
                section_option.find('.extra_selection').addClass('show');
                section_details.show('fast');
                section_features.hide();
                section_close.show();
            }
    
            return false;
            
        });
	}

});

// nsb-timetable.js
jQuery(document).ready(function($) {
    
    // TIMETABLE
    timetable_init();
    
    // initialize timetable
    function timetable_init() {
        
        // timetable select week
        $('#timetable-select-week td').mouseover(function() {
            $(this).parent().addClass('hover');
            
        });
        
        $('#timetable-select-week td').mouseout(function() {
            $(this).parent().removeClass('hover');
        });

        $('#timetable-select-week a').click(function() {
            $('#timetable-select-week tr').removeClass('selected');
            $(this).parent().parent().addClass('selected');
        });

        // select scope for info timetable
        $('#timetable-info-search .scope').change(function() {
            $('#timetable-info-search .options').toggle();
        });

        // outward scope
        $('#timetable-info-search .options .outward .scope-outward').change(function() {
            
            if ($(this).is(':checked')) {
                $('#timetable-info-search .options .outward p').removeClass("disabled");
                $('#timetable-info-search .options .outward .days input[type=checkbox]').attr("disabled","");
                $('#timetable-info-search .options .outward .time select').attr("disabled","");
            } else {
                $('#timetable-info-search .options .outward p').addClass("disabled");
                $('#timetable-info-search .options .outward .days input[type=checkbox]').attr("disabled","disabled");
                $('#timetable-info-search .options .outward .time select').attr("disabled","disabled");
            }

        });
        
        // return scope
        $('#timetable-info-search .options .return .scope-return').change(function() {
            
            if ($(this).is(':checked')) {
                $('#timetable-info-search .options .return p').removeClass("disabled");
                $('#timetable-info-search .options .return .days input[type=checkbox]').attr("disabled","");
                $('#timetable-info-search .options .return .time select').attr("disabled","");
            } else {
                $('#timetable-info-search .options .return p').addClass("disabled");
                $('#timetable-info-search .options .return .days input[type=checkbox]').attr("disabled","disabled");
                $('#timetable-info-search .options .return .time select').attr("disabled","disabled");
            }

        });
        
        // show/hide station details
        $("#article .timetable a.stations, #article .timetable .arrive a, #article .timetable .depart a").click(function() {
            
            
            var journey_stations = $(this).parent().parent().nextUntil('tr.option').not('tr.details');
            journey_stations.toggle();			

            return false;
            
        });

        // show/hide message details
        $("#article .timetable .message a.showmore").click(function() {
            
            var message_details = $(this).parent().parent().find('span');
            var message_more = $(this).parent().parent().find('em');
            message_details.toggle();			
            message_more.toggle();			

            return false;
            
        });
    }
});

// nsb-newsticker.js
jQuery(document).ready(function($) {
    $("#ticker ul").newsticker(); // or $("#news").newsTicker(5000);							
});


$(document).ready(function($) {
    $('input#sendEmail').click(function() {
        if ($(this).parents('form').valid())	{
            articleId = $(this).parent().find('input[name=articleid]').val();
            from=$(this).parent().find('input[name=email_from]').val();
            to=$(this).parent().find('input[name=email_to]').val();
            
            if (articleId != null && from != null  && to != null) {
                if (articleId != '' && from != ''  && to != '') {
                    $.getJSON(htmlroot+'/javascript/sendArticleTip.php', {'from':from, 'to':to, 'articleId': articleId}, function(data) {
                        if (data[0].error != undefined) {
                            var row  = data[0].error;
                            $("#toolbar-email").html(row);
                        } else if (data[0].text != undefined) {
                            var row = data[0].text;
                            $("#toolbar-email").html(row);
                        }
                        
                    });
                }
            }
        }
        return false;
    });     
});

$(document).ready(function($) {
    var dates = $('#contactusfeedback-date').datepicker( {
        dateFormat : "dd.mm.yy",
        firstDay : 1,
        numberOfMonths : 1,
        minDate : '-6m',
        maxDate : '+0d'
    });
});

(function($){ 
  jQuery.fn.idle = function(time)  { 
      var o = $(this); 
      o.queue(function()      { 
         setTimeout(function() { 
            o.dequeue(); 
         }, time);
      });
  };
})(jQuery);

// nsb-menu.js
(function($) {
    $.fn.activeMenu = function() {
        var priv = {
            isActive: false,	// True when a menu is open
            isInvoked: false,	// True when a menu item has been clicked
            isLoginOpen: false,	// True when login dialog is open
            activeMenu: 0,		// The index of menus[] currently active
            activeSub: 0,		// The index of menus[sub[]] currently active
            mouseOn: false,		// True when invoked by mouse hover
            keybOn: false,		// True when invoked by keyboard action
            menus: [],			// Menu repository

            // Triggers
            preventDefault: function(evt) {
                evt.preventDefault();
                evt.stopPropagation();
            },

            /** Open the menu **/
            onOpen: function(evt, target, index) {
                var me = this;

                // Prevent multiple executions of this method
                if (!priv.isLoginOpen && (!priv.isActive || priv.activeMenu != index))	{
                    // Clean up old fun
                    if (priv.isActive && !$(target.menu).hasClass('open')) {
                        priv.onClose.call(this, evt, true);
                    }

                    // Detect type of motion responsible for opening this menu
                    if (evt.type == "keydown") priv.keybOn = true;
                    if (evt.type == "mouseenter") priv.mouseOn = true;

                    // Prevent this setting an infinite recursion
                    if (!$(target.menu).hasClass('open')) {
                        $(target.menu).addClass('open').find("ul").show(); 	// Drop down the subnav on hover
                        priv.onHighlight.call(this, evt, target.anchor, 0);	// Highlight top anchor
                    }
                    $(window).click(function(evt) { 
                        priv.onClose.call(me, evt, true); 
                    });
                    priv.isActive = true;
                    priv.activeSub = 0;
                    priv.activeMenu = index;
                }
            },

            /** Close the menu **/
            onClose: function(evt, calledInternal) {
                if (!calledInternal && priv.isActive && priv.keybOn && (evt.type != "keyup" && evt.type != "keydown")) 
                    return;
                $(".simHover").removeClass("simHover");							// Remove anchor highlight
                $('.open', priv.menuBar).removeClass('open').find("ul").hide(); // Hide the subnav
                $(window).unbind("click");
                priv.isActive = false;
                priv.activeMenu = 0;
                priv.activeSub = 0;
                priv.keybOn = false;
                priv.mouseOn = false;
            },
            
            /** Highlight a menu item **/
            onHighlight: function(evt, target, index) {
                $(".simHover").removeClass("simHover");
                $(target).addClass("simHover");//.focus();
                priv.activeSub = index;
            },
            
            /** Simulate a click on a menuitem **/
            onInvoke: function(evt, target, index) {
                priv.preventDefault.call(this, evt);
                if (target.menu && !$(target.menu).hasClass("submenu")) {
                    return priv.doLogin.call(this);
                }
                var a = $(target.sub[priv.activeSub]).find('a'); 
                window.location.href = a.attr("href");
            },
            
            /** Handle login box open/shut **/
            doLogin: function() {
                var me = this;
                // Setup dialog close event
                var dClose = function(evt) {
                    if (evt.type == "keydown" && evt.keyCode != 27) return;
                    
                    $("#login-overlay").dialog('close');	// Close dialog
                    $('body').unbind("keydown", dClose);	// Unbind ESC key event from body
                    $("#login-overlay .close a").unbind("click", dClose);
                    priv.isLoginOpen = false;				// Revoke local flag on login open
                    priv.onClose.call(me, evt);				// Close menu item
                    return false;
                }
                $("#login-overlay .close a").bind("click", dClose);					// Attach click listener for close anchor
                $('body').keydown(dClose);											// Attach key listener on body, listening for ESC
                $("#login-overlay").dialog({ modal: true, closeOnEscape: false });	// Invoke dialog
                priv.isLoginOpen = true;
                return false;
            },
            
            /** Attach events on the DOM **/
            attachEvents: function() {
                var me = this;
                var getIndexInSub = function (el, menu) {
                    for (var index = 0; menu.sub.length > index; index++) {
                        if ($('a', menu.sub[index])[0] == $(el)[0])	
                            return index;
                    }
                };
                // Retreive menu structure from DOM, 
                $('li.submenu > a, #login > a', me.menuBar).each(function(index, item) {
                    var m = priv.menus[index] = {"menu": $(item).parent(), "anchor": $(item), "sub": $(item).parent().add($(item).parent().find('ul li')) };
                    
                    // and setup triggers
                    $(m.menu).hover(function(evt) { priv.onOpen.call(me, evt, m, index); }, function(evt) { priv.onClose.call(me, evt); });
                    $(m.anchor).focus(function(evt) { priv.onOpen.call(me, evt, m, index); }); //.blur(function(evt) { priv.onClose.call(me, evt); });
                    $(m.anchor).click(function(evt) { priv.onInvoke.call(me, evt, m, index); });
                    $(m.sub).find('a').click(function(evt) { priv.onInvoke.call(me, evt, m, index); });
                    $(m.sub).find('a').mouseover(function(evt) { priv.onHighlight.call(me, evt, this, getIndexInSub(this, m)); });
                });
                
                // Setup keymapper
                var keys = { ALT: 18, ESC: 27, SPACE: 32, ENTER: 13, RIGHT: 39, LEFT: 37, DOWN: 40, UP: 38 };
                var isKeyInConf = function(key) {
                    for (k in keys)  { if (key == keys[k]) { return true }}; 
                    return false;
                }
                
                var currentKey = null;
                
                $(document).keyup(function(evt) {
                    if (evt.altKey && evt.keyCode != 18 || !isKeyInConf(evt.keyCode)) return; // Prevent reacting to keycombos or keys out of this scope
                    if (evt.keyCode != currentKey) return;
                    priv.keybOn = true;
                    var i = priv.activeMenu,
                    m = priv.menus[i];
                    
                    switch (evt.keyCode) {
                        case keys.ALT:
                            priv.preventDefault.call(me, evt);
                            priv.isActive ? priv.onClose.call(me, evt) : priv.onOpen.call(me, evt, m, i);
                            break;
                    }
                });
                
                $(document).keydown(function(evt) {
                    currentKey = evt.keyCode;
                    if (!isKeyInConf(evt.keyCode) || !priv.isActive)  return;
                    priv.keybOn = true;
                    var i = priv.activeMenu,
                    m = priv.menus[i];
                    
                    switch (evt.keyCode) {
                        case keys.ESC: 
                            priv.preventDefault.call(me, evt);
                            priv.onClose.call(me, evt);
                            break;
                        case keys.SPACE:
                        case keys.ENTER:
                            if (priv.isActive) priv.onInvoke.call(me, evt, m, i);
                            break;
                        case keys.RIGHT:
                            if (priv.isActive && priv.menus.length > i + 1) {
                                priv.preventDefault.call(me, evt);
                                priv.onOpen.call(me, evt, priv.menus[i+1], i+1);
                            }
                            break;
                        case keys.LEFT:
                            if (priv.isActive && priv.activeMenu > 0) {
                                priv.preventDefault.call(me, evt);
                                priv.onOpen.call(me, evt, priv.menus[i-1], i-1);
                            }
                            break;
                        case keys.DOWN:
                            if (priv.isActive && m.sub.length > priv.activeSub + 1) {
                                priv.preventDefault.call(me, evt);
                                priv.onHighlight.call(me, evt, $(m.sub[priv.activeSub + 1]).find('a'), priv.activeSub + 1);
                            }
                            break;
                        case keys.UP:
                            if (priv.isActive && priv.activeSub > 0) {
                                priv.preventDefault.call(me, evt);
                                var target = (priv.activeSub - 1 == 0 ? $(m.anchor) : $(m.sub[priv.activeSub - 1]).find('a'));
                                priv.onHighlight.call(me, evt, target, priv.activeSub - 1);
                            }
                            break;
                        default:
                    }
                });
            }
        }

        /** Construct a new instance of the active menu handler **/
        return this.each(function() { 
            var menuBar = this.menuBar = $(this);
            
            $('ul li ul', menuBar).parent().addClass("submenu");
            priv.attachEvents.call(this);
        });
    }
})( jQuery );
$(function() { $("#menu").activeMenu(); });


/* Function to change the routes on region purchase step 2' */

$(document).ready(function($) {
    $('#checkout table.journey tbody tr.option td.select input').click(function() {
        //disable the submit button while calling webserver. NB: If the call gives an error, handle this as well.
        $('#selectjourney-submit_form').attr('disabled', 'disabled' ).addClass( 'disabled' );
        var trip_type=$(this).attr('name');
        var full_val = $(this).attr('value');
        var price = (full_val.substring(0,1) == 'f') ? 'full': 'low';
        var id = full_val.substring(1);
        $.getJSON(htmlroot +'/javascript/region_ticket_change_route_alternative.php', {'trip_type': trip_type,'id': id, 'price':price}, function(data) {
            if (data[0].error == undefined) {
                var total=0;
                if (data[0].outward != undefined) {
                    $("#outward-date").html(data[0].outward.date);
                    $("#outward-depart th strong").html(data[0].outward.deptime);
                    $("#outward-arrive th strong").html(data[0].outward.arrtime);
                    $("tr.outward-product").remove();
                    $("tr#outward-subtotal").remove();
                    var html='';
                    while (passenger = data[0].outward.passengers.pop()) {
                        html += '<tr class="product outward-product">';
                        html += '<th>'+passenger.text+'</th>';
                        html += '<td><span class="value">'+passenger.price+',-</span></td>';
                    }
                    html += '<tr class="subtotal" id="outward-subtotal">';
                    html += '<th>'+data[0].outward.price.text+'</th>';
                    html += '<td><span class="value">'+data[0].outward.price.price+',-</span></td>';
                    total += data[0].outward.price.price;
                    $("tr#outward-arrive").after(html);
                    
                }
                if (data[0].back != undefined) {
                    $("#return-date").html(data[0].back.date);
                    $("#return-depart th strong").html(data[0].back.deptime);
                    $("#return-arrive th strong").html(data[0].back.arrtime);
                    $("tr.return-product").remove();
                    $("tr#return-subtotal").remove();
                    var html='';
                    while (passenger = data[0].back.passengers.pop()) {
                        html += '<tr class="product return-product">';
                        html += '<th>'+passenger.text+'</th>';
                        html += '<td><span class="value">'+passenger.price+',-</span></td>';
                    }
                    html += '<tr class="subtotal" id="return-subtotal">';
                    html += '<th>'+data[0].back.price.text+'</th>';
                    html += '<td><span class="value">'+data[0].back.price.price+',-</span></td>';
                    total += data[0].back.price.price;
                    $("tr#return-arrive").after(html);
                }
                $("#total-summary tr.total th span.value").html(total);
            } //.error -end

            //re-enable button
            $('#selectjourney-submit_form').removeAttr('disabled').removeClass( 'disabled' );
        }); //End AJAX-call
        //Setting new styling.
        var journeyclass= (trip_type == 'departure') ? 'outward' : 'return';
        var cells = $("#checkout div#journey-"+journeyclass+" tr td");
        var rows = $("#checkout div#journey-"+journeyclass+" tr");
        
        //remove all classes
        cells.removeClass('on');
        rows.removeClass('selected');
        
        // hide all section info
        var journey_sections =  $("#journey-"+journeyclass+" tbody tr.section");
        journey_sections.hide();            
        
        // get journey and sections
        var journey = $(this).parent().parent().parent();
        var journey_price = $(this).parent().parent();
        var journey_sections = $(this).parent().parent().parent().nextUntil('tr.option');
        
        // add classes      
        journey.addClass('selected');
        journey_price.addClass('on');
        journey_sections.addClass('selected');
        
        rows.removeClass("prev-row");
        
        //styling of the border on the previous row
        $("#journey-"+journeyclass+" tbody tr.row-"+(id-1)).addClass('prev-row');
        
        // show section info
        journey_sections.show();
        
        // set class to open when sections are shown
        rows.removeClass("open");
        
        if (journey_sections.length > 1) {
            $("#journey-"+journeyclass+" tbody tr.selected").addClass('open');
        }
        
        
    }); //End click-function
    
    // initial styling of the border on the previous row
    $('#checkout table.journey tbody tr.option td.select input:checked').each(function(index) {
        var trip_type=$(this).attr('name');
        var journeyclass= (trip_type == 'departure') ? 'outward' : 'return';
        var full_val = $(this).attr('value');
        var id = full_val.substring(1);
        $("#journey-"+journeyclass+" tbody tr.row-"+(id-1)).addClass('prev-row');
    });
});

/**
 * Function to update price and selections on stage 3 
 */
$(function() {
    $('#services_form #checkout .service .select input[type="radio"]').removeAttr('onclick');
    $('#services_form #checkout .service .select input[type="radio"]').click(function(evt) {
        $('#services_form-complete_step').attr('disabled', 'disabled' ).addClass( 'disabled' );
        var form_id   = $(this).parents('form').attr('id');
        var input_id  = $(this).attr('name');
        
        var trip_type = input_id.substring(input_id.indexOf('-')+1, input_id.lastIndexOf('-'));
        var stage     = input_id.substring(input_id.lastIndexOf('-')+1, input_id.length);
        var compartment_type = $(this).val();
        var noCompartments = $(this).parents('td').find('.extra_selection select').val();
        if (noCompartments == undefined) {
            //not a sleeping comp.
            noCompartments=0;
        }
        
        $.getJSON(htmlroot +'/javascript/region_ticket_change_compartment_type.php', {'trip_type': trip_type, 'stage': stage, 'compartment_type': compartment_type, 'noCompartments': noCompartments}, function(data) {
            if (!data[0].error){
                // Change summary table
                $('#summary .outward-product th').each(function(index, item)         {	$(this).html(data[0].outward_product[index].text);  });
                $('#summary .outward-product span.value').each(function(index, item) {  $(this).html(data[0].outward_product[index].value); });
                $('#summary #outward-subtotal span.value').html(data[0].outward_subtotal);
                
                $('#summary .return-product th').each(function(index, item)          {  $(this).html(data[0].return_product[index].text);   });
                $('#summary .return-product span.value').each(function(index, item)  {  $(this).html(data[0].return_product[index].value);  });
                $('#summary #return-subtotal span.value').html(data[0].return_subtotal);
                $('#total-summary span.value').html(data[0].total); // Total sum
                
                //Setting the selected compartment types
                var outstages = data[0].outward_stages;
                for (var i in outstages) {
                    //Select it
                    var el = $('#services_form-departure-'+i+'-'+outstages[i])
                    el.attr('checked', "checked");
                    //set styling
                    
                    // get journey and sections
                    var stages           = el.parents('#checkout').find('table.service');
                    var section          = el.parents('tbody');
                    var section_cell     = el.parents('td');
                    var section_option   = el.parents('tr');
                    var section_features = $(section_option).find('td.features a span.open');
                    var section_close    = $(section_option).find('td.features a span.close');
                    var section_details  = $(section_option).next('tr.details');
                    var section_previous = $($(section_option).prevAll('tr.option')[0]);

                    // remove classes
                    section.find('tr').removeClass('selected');
                    section.find('td').removeClass('on');
                    
                    // add class        
                    section_cell.addClass('on');
                    section_option.addClass('selected');
                    section_details.addClass('selected');

                }
                var retstages=data[0].return_stages;
                for (var i in retstages) {
                    var el = $('#services_form-return-'+i+'-'+retstages[i]);
                    el.attr('checked', "checked");
                    var stages           = el.parents('#checkout').find('table.service');
                    var section          = el.parents('tbody');
                    var section_cell     = el.parents('td');
                    var section_option   = el.parents('tr');
                    var section_features = $(section_option).find('td.features a span.open');
                    var section_close    = $(section_option).find('td.features a span.close');
                    var section_details  = $(section_option).next('tr.details');

                    // remove classes
                    section.find('tr').removeClass('selected');
                    section.find('td').removeClass('on');
                
                    // add class        
                    section_cell.addClass('on');
                    section_option.addClass('selected');
                    section_details.addClass('selected');
                }
            }
        });
        $('#services_form-complete_step').removeAttr('disabled').removeClass( 'disabled' );
        
    });
});

// Stage 4 - checkout
/* nsb-checkout-details.js */
jQuery(document).ready(function($) {
    
    // details
    details_init();
    
    // initialize details
    function details_init() {
        
        // GIFTCARD
        $('#checkout-giftcard input[name=giftcertificate_valuecode][type=text]').
        click(function() { $('#giftcertificate_recaptca').css('display', 'inline-block'); });
        $('#checkout-giftcard input[name=giftcertificate_valuecode][type=text]').
        change(function() { $('#giftcertificate_recaptca').css('display', 'inline-block'); });
        $('#discounts-summary input[type=checkbox][name=giftcard]').change(function() {
            remove_gift_certificate (this);
        });
    
        // use giftcard
        $('#checkout-giftcard input[type=button]').click(function() {
            var valueCode = $('#checkout-giftcard input[name=giftcertificate_valuecode][type=text]').val();
            
            if(valueCode != '') {
                $('#giftcertificate_recaptca').css('display', 'inline-block');
            }
        
            $('#checkout-giftcard .error').hide();
            $('#checkout-giftcard .message p em').html('Laster ...');
            $('#checkout-giftcard .message').show();
            $.post(htmlroot+'/javascript/giftcertificates.php', {
                'valueCode': valueCode,
                'recaptcha_challenge_field': $('#recaptcha_challenge_field').val(),
                'recaptcha_response_field': $('#recaptcha_response_field').val(),
                'region_purchase_addtosession': '1'
            },
            function (data) {
                Recaptcha.reload();
                if(data[0].result == 'ok') {
                    details_giftcertificate_success (data[0])
                }
                else {
                    // Show error message
                    $('#checkout-giftcard .message').hide();
                    
                    $('#checkout-giftcard .error p strong').html(data[0].error);
                    $('#checkout-giftcard .error').show();
                }
            },
            'json'
            ).
            error(function () {
                Recaptcha.reload();
                
                // Show error message
                $('#checkout-giftcard .message').hide();
                
                $('#checkout-giftcard .error p strong').html('En teknisk feil har oppstått.');
                $('#checkout-giftcard .error').show();
            });
        });
        function details_giftcertificate_success (giftcertificate) {
            //var value = $('#checkout-giftcard input[type=text]').val() * 1;
            var total = $('#total-summary .total .value').html().replace(' ','');

            // only add cards if total over 0 and giftcard has value
            if (giftcertificate.regionpurchase_amountused > 0) {
                // Add status text
                var date = new Date(giftcertificate.giftcertificate_validtodate*1000);
                var month = date.getMonth()+1; // 0-11
                var expiredate = date.getDate() + '.' + month + '.' + date.getFullYear() + '.';
                var status_text = 'Restbeløp: kr '+(giftcertificate.regionpurchase_new_remaining_formatted)+'. Utløpsdato: '+expiredate;
                $('#checkout-giftcard .message p em').html(status_text);
                $('#checkout-giftcard input[type=text]').val('');

                // hide errors, show message
                $('#checkout-giftcard .error').hide();
                $('#checkout-giftcard .message').show();

                // show giftcard in summary
                $('#discounts-summary').show();
                
                // Add the new gift certificate
                var value = (giftcertificate.regionpurchase_amountused)*1;
                giftcertificate_add (giftcertificate.giftcertificate_valuecode, value);
                
                // Update total with new value from server
                $('#total-summary .total .value').html(giftcertificate.regionpurchase_new_total);

                free_or_pay(giftcertificate.regionpurchase_new_total);
            }
            
            return false;
    
        }
    
    function remove_gift_certificate (giftcertificate_element) {
        $.post(htmlroot+'/javascript/giftcertificates.php', {
            'valueCode': $(giftcertificate_element).attr('id'),
            'region_purchase_removefromsession': '1'
        },
        function (data) {
            Recaptcha.reload();
            if(data.result == 'ok') {
                // Update total that is displayed
                $('#total-summary .total .value').html(data.regionpurchase_new_remaining);
                
                // Remove all product lines and update with the new elements
                //$(giftcertificate_element).parent().parent().parent().remove();
                $('#discounts-summary .product').remove();
                jQuery.each(data.giftcertificates_left, function (i, val) {
                    giftcertificate_add (val.valuecode, val.amountused);
                });
                
                free_or_pay(data.regionpurchase_new_remaining);
            }
            else {
                // Nothing happens...
            }
        },
        'json'
        ).
        error(function () {
            // Nothing happens...
        });
    }
        
        // free trip or pay for it?
        function free_or_pay(new_total) {
            // remove cards if total == 0
            if (new_total > 0) {
                $('#checkout-payment-select').show();
                $('#checkout-payment-save').show();
                $('#checkout-payment-free').hide();
            } else {
                $('#checkout-payment-select').hide();
                $('#checkout-payment-save').hide();
                $('#checkout-payment-free').show();
            }

            if(typeof purchaseregion_update_submitbutton == 'function') {
            	purchaseregion_update_submitbutton();
            }
        }

        // Initialize payment information dependent on if there is a payment to be made or not
        if($('#total-summary .total .value').length) {
        	free_or_pay($('#total-summary .total .value').html());
        }
        
        function giftcertificate_add (valuecode, amountused) {
            // how many cards?
            var cards = $('#discounts-summary tr').size();
            var giftcard_id = cards+1;
            
            // Add new item in shopping cart
            var giftcard = $('#discounts-summary').append(
                            '<tr class="product" id="giftcard-'+giftcard_id+'">'+
                            '<th><label><input type="checkbox" name="giftcard" checked="checked" id="' + valuecode + '" /> Gavekort</label></th>'+
                            '<td>&minus;<span class="value">'+amountused+'</span>,-</td>'+
                            '</tr>');

            // make giftcard removeable
            $('#giftcard-'+giftcard_id+'').find('input').change(function() {
                remove_gift_certificate (this);
            });
        }
        

        // CREDITCARD
        
        // show/hide new card and update submitbutton
        $('#checkout-payment input[type=radio]').change(function()	{
            $('#checkout-payment .new').toggle($('#customerdetails_form-paycard_new').is(':checked'));
            
            if(typeof purchaseregion_update_submitbutton == 'function') {
                purchaseregion_update_submitbutton();
            }
        });
    }

});


/**
 * Mypage function for looking up postal codes
 */
$(function() {
    var origCode = $('#mypage_edituser-post_code').val();
    var origPlace = $('#mypage_edituser-post_place').html();
    $('#mypage_edituser-post_code').change(function(evt) {
        var cur = $(this).val();
        if (cur != origCode) {
            $('#mypage_edituser-post_place_span').html(" ... ");
            $.getJSON(httpprotocol+'://fraktguide.bring.no/fraktguide/postalCode.json?pnr='+cur+'&callback=?',
                function (data) {
                    if (data.result) {
                        $('#mypage_edituser-post_place').val(data.result);
                        $('#mypage_edituser-post_place_span').html(data.result);
                    } 
                    else {
                        $('#mypage_edituser-post_place').val('');
                        $('#mypage_edituser-post_place_span').html('&nbsp;');
                    }
                }
            );
        } else {
            $('#mypage_edituser-post_place').html(origPlace);
        }
    });
});

/**
 * Gift certificate buy function for looking up postal codes
 */
$(function() {
    var origCode = $('#gift-post_code').val();
    var origPlace = $('#gift-post_place').html();
    $('#gift-post_code').change(function(evt) {
        var cur = $(this).val();
        if (cur != origCode) {
            if($('#gift-post_place').length <= 0) {
                return;
            }
            $('#gift-post_place_span').html(" ... ");
            $.getJSON(httpprotocol+'://fraktguide.bring.no/fraktguide/postalCode.json?pnr='+cur+'&callback=?',
                function (data) {
                    if (data.result) {
                        $('#gift-post_place').val(data.result);
                        $('#gift-post_place_span').html(data.result);
                    } 
                    else {
                        $('#gift-post_place').val('');
                        $('#gift-post_place_span').html('&nbsp;');
                    }
                }
            );
        } else {
            $('#gift-post_place').html(origPlace);
        }
    });
});

/**
 *  These methods and variables is copied from Coretreks cplib.js
 *  cpNavigatorUserAgent, cpNavigatorUserAgentInfo, 
 *  cpWriteMediaObject(...), cpReadCookie(...), getQueryParamsFromObject(...)
 */
var cpNavigatorUserAgent = navigator.userAgent.toLowerCase() ;
var cpNavigatorUserAgentInfo = {
    isIE     : (cpNavigatorUserAgent.indexOf('msie')>-1),
    isIE7    : (cpNavigatorUserAgent.indexOf('msie 7')>-1),
    isGecko  : (cpNavigatorUserAgent.indexOf('gecko/')>-1),
    isSafari : (cpNavigatorUserAgent.indexOf('safari')>-1),
    isOpera  : (cpNavigatorUserAgent.indexOf('opera')>-1),
    isMac    : (cpNavigatorUserAgent.indexOf('macintosh')>-1)
};

/**
 *  Function used to print flash and movies inline
 *
 *  *) These settings might not work in all browser plugins
 *
 *  @src         string The full URL to the video
 *  @sessionName string The session name where users sessionid is stored (used for IE)
 *  @width       int The width
 *  @height      int The height
 *  @mimetype    string The files mimetype
 *  @loop        boolean Whether or not to loop the video *
 *  @autoplay    boolean Whether or not to start the video when it's loaded *
 *  @controller  boolean Whether or not to include plugin controllers *
 */
function cpWriteMediaObject(src, sessionName, width, height, mimeType, loop, autoplay, controller, objId){
    var objectSettings = '';

    // Detect protocol for codebase
    var codebaseProtocol = (src.substr(0,5)=='https'?'https':'http');

    // Check if this is a flash movie
    var isFlashMovie = new Object();
    
    isFlashMovie['video/x-flv'] = true;
    isFlashMovie['application/x-flash-video'] = true;
    isFlashMovie['video/x-flv'] = true;

    if (isFlashMovie[mimeType] != null){    
        var flashVars = new Object();         
        flashVars["file"] = encodeURIComponent(src);
        flashVars["width"] = width;
        flashVars["height"] = height;       
        //flashVars["displayheight"] = height+; // set to same as height for floating controls
        flashVars["overstrech"] = 'true';
        flashVars["frontcolor"] = '0xFFFFFF';
        flashVars["backcolor"] = '0x000000';
        flashVars["lightcolor"] = '0xFFFFFF';
        flashVars["autostart"] = autoplay?'true':'false';
        flashVars["repeat"] = loop?'true':'false';
        flashVars["usefullscreen"] = 'true';

        // Add flash movie parameters
        objectSettings += '<param name="allowscriptaccess" value="always" />';
        objectSettings += '<param name="allowfullscreen" value="true" />';
        objectSettings += '<param name="flashvars" value="' + getQueryParamsFromObject(flashVars) + '" />';

        mimeType = 'application/x-shockwave-flash';
        src = CPLIBHTMLROOT +'/mediaplayer.swf';
    }

    // Handling IE specialties
    var rewriteMimeType = new Object();
    if (cpNavigatorUserAgentInfo.isIE){
    
        rewriteMimeType['audio/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/mpeg'] = 'application/x-mplayer2';
        rewriteMimeType['video/x-msvideo'] = 'video/x-ms-wmv';
    }
    // In some cases we must change the mimetype for IE :/
    if (rewriteMimeType[mimeType] != null){
        mimeType = rewriteMimeType[mimeType];
    }

    // Add object parameters
    if (mimeType != 'application/x-shockwave-flash') {    
        objectSettings += '<param name="loop" value="' +(loop?'true':'false') +'" />';
        objectSettings += '<param name="autostart" value="' +(autoplay?'true':'false') +'" />';
        objectSettings += '<param name="controller" value="' +(controller?'true':'false') +'" />';
    } else {
        objectSettings += '<param name="wmode" value="opaque" />';
    }

    // IE: We need to add sessionid to the URL in order for the video plugin to use the same session
    //     as IE. If sessionid is not sent, the video plugin will try to load the URL without a valid
    //     session causing the session to be destoyed.
    //     -----------------------------
    //     NOTE from Kurt: The session id broke together with the new JW FLV player. I first tried removing
    //     this alltogether, and it seem to work, event with user protected files. I can't get it
    //     to break whatever I do. To be sure not to reintroduce old bugs, I move this session stuff
    //     down here. This way it will be added for the non JW FLV players.
    if (cpNavigatorUserAgentInfo.isIE){    
        var sep = (src.indexOf('?') > -1?'&':'?');     
        var sessionID = cpReadCookie(sessionName);           
        if (sessionID != null && sessionID.length > 0){
            var src = src +sep +sessionName +'=' +sessionID;
        }
    }

    // Build object tag and content
    var objectString = '';
    var objectStringStart = '<object type="' +mimeType +'" data="' +src +'" width="' +width +'" height="' +height +'">';
    var objectStringName = '<param name="movie" value="' +src +'" />';
    var objectStringFallback = '<p>(No plugin detected for your OS/browser)</p>';
    var objectStringEnd = '</object>';
    switch (mimeType) {
        case 'application/x-shockwave-flash':
            if (cpNavigatorUserAgentInfo.isIE){            
                var objectStringStart = '<object codebase="'+codebaseProtocol+'://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab" classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" width="' +width +'" height="' +height +'">';
            }
            break;
        case 'application/x-mplayer2':
        case 'video/x-ms-wmv':
        case 'video/x-msvideo':
            // WMV, MPEG
            objectStringName = '<param name="src" value="' +src +'" />';
            break;

        case 'video/quicktime':
            // Quicktime in IE
            if (cpNavigatorUserAgentInfo.isIE){
                objectStringStart = '<object classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B" codebase="'+codebaseProtocol+'://www.apple.com/qtactivex/qtplugin.cab" width="' +width +'" height="' +height +'">';
                objectStringName  = '<param name="src" value="' +src +'" />';
                break;
            }
            break;

        case 'video/x-ms-asf':
            // ASF in IE
            if (cpNavigatorUserAgentInfo.isIE){
                objectStringName = '<param name="FileName" value="' +src +'" />';
                break;
            }
            break;

        default:
            break;
    }

    objectString += objectStringStart;
    objectString += objectStringName;
    objectString += objectSettings;
    objectString += objectStringFallback;
    objectString += objectStringEnd;

    try {
        document.getElementById(objId).innerHTML = objectString;
    } catch(e){
        document.write(objectString);
    }
}

/**
 *  Function that reads a cookies value. Returns null if the requested cookie is not found
 */
function cpReadCookie(cookieName){
    cookieName += '=';
    var cookies = document.cookie.split(';');
    for (var i=0; i<cookies.length; i++){
        var cookie = cookies[i];
        while (cookie.charAt(0)==' ') cookie = cookie.substr(1);
        if (cookie.indexOf(cookieName) == 0) return cookie.substr(cookieName.length);
    }
    return null;
}

