﻿/*

	Scandlines
	JavaScript functions
	
	Author: Creuna Danmark A/S / www.creuna.dk
	Copyright: 2009, Creuna Danmark A/S. All rights resevered

-----------------------------------------------------------------------*/

//jQuery.noConflict();

var Scandlines = {

    init: function() {

        //set footer
        //Scandlines.footer.setFooter();

        Scandlines.search.init();

        //init datepicker
        if (jQuery('.dateField').length) {
            Scandlines.datepicker.init();
        }


        //init timepicker
        if (jQuery('.timeField').length) {
            Scandlines.timepicker.init();
        }


        //init rotating box
        if (jQuery('#rotatingOfferBox').length) {
            Scandlines.productOffers.prepare();
        }

        if (jQuery('.categoryDetails').length) {
            Scandlines.categoryDetails.init();
        }

        if (jQuery('.reductionBlock').length) {
            Scandlines.saveup.init();
        }

        if (jQuery('.vehicleTypes input').length) {
            Scandlines.routeBookingForm.init();
        }

        if (jQuery('.pdfForm').length) {
            Scandlines.pdfForm.init();
        }

        if (jQuery("li[id*='uiSubCategory']").length) {
            Scandlines.expandedCategoryCookie.expand();
        }

        if (jQuery('.vote input[type="radio"]').length) {
            Scandlines.quickPoll.fixGroupNames();
            Scandlines.quickPoll.addClickHandlers();
        }

        if (jQuery('#scandlinesMap').length) {
            Scandlines.map.init('frontpage');
        }

        if (jQuery('.routeOverviewMap').length) {
            Scandlines.map.init('routesOverview');
        }

        if (jQuery('#brobizz').length) {
            Scandlines.brobizz.init();
        }

        if (jQuery('#pbs').length) {
            Scandlines.pbs.init();
        }

        if (jQuery('ul.doubleField').length) {
            Scandlines.autobizz.init();
        }


        if (jQuery('#orderScandlinesCard').length) {
            Scandlines.card.init();
        }

        jQuery('#faq').accordion({
            active: false,
            header: 'h3',
            autoheight: false
        });

        jQuery('.offer').click(function(event) {
            if ((jQuery(event.target).parent().attr('class') == 'seeAll') || (jQuery(event.target).parent().attr('class') == 'preorderLink')) {
                window.location = jQuery(event.target).attr('href');
            }
            else {
                if ((jQuery(event.target).attr('type') != 'text') && (jQuery(event.target).attr('type') != 'button')) {
                    window.location = jQuery(this).find('a.toProductPage.active').attr('href');
                }
            }
        });


        Scandlines.icons.init();
        Scandlines.links.init();

    },
    search:
    {
        init: function() {
            $('#header .searchBox input[type="text"]').keypress(function(e) {
                if (e.keyCode == 13) { Scandlines.search.doSearch(); return false; }

            })
        },
        doSearch: function() {
            var valueToSearch = jQuery('input[id*="uiTxtSearchPhrase"]').val();
            if (valueToSearch) {
                var searchLocation = jQuery('span#searchPageUrl').text();
                var searchPhrase = jQuery('span#searchPhrase').text();
                searchLocation = searchLocation + '?' + searchPhrase + '=' + valueToSearch;
                window.location = searchLocation;
            }
            return false;
        }

    },
    icons:
    {
        init: function() {
            //timepicker & datepicker icons
            if (jQuery('.customTimeField').length) {
                jQuery('input.routeBookingField.dateField').parent().prepend('<a href="#" class="showDatepicker"></a>');
                jQuery('input.customTimeField.timeField').parent().prepend('<a href="#" class="showTimepicker"></a>');
                jQuery('a.showDatepicker, a.showTimepicker').click(function() {
                    jQuery(this).parent().find('input').focus();
                    return false;
                });

                $('input.customTimeField.timeField').change(function() {
                    Scandlines.timepicker.updateTimeField(jQuery(this))
                });
            }
        }

    },
    popups:
    {
        init: function() {
            jQuery('#popup_container.warning').remove();
            jQuery('body').append('<div id="popup_container" class="warning" style="display: none;"><h1 id="popup_title">' + jQuery('#dangerousCargoWarningTitle').text() + '</h1><div id="popup_content" class="alert"><div id="popup_message">' + jQuery('#dangerousCargoWarningText').text() + '</div></div>');
            jQuery('span.dangerousCargoWarning').mouseover(function(e) {
                var mouseX = 0;
                var mouseY = 0;
                mouseX = e.pageX;
                mouseY = e.pageY;
                jQuery('#popup_container.warning').css(
                        {
                            'left': (mouseX + 10) + 'px',
                            'top': (mouseY - 10) + 'px',
                            'position': 'absolute'
                        }
                    );
                jQuery('#popup_container.warning').show('fast');
            });
            jQuery('span.dangerousCargoWarning').mouseout(function() {
                jQuery('#popup_container.warning').hide('fast');
            });

        }
    },

    saveup:
	{
	    init: function() {
	        jQuery('.reductionBlock').each(function() {
	            priceWidth = jQuery(this).prev('.priceBlock').width();
	            saveWidth = jQuery(this).width();
	            if (priceWidth < saveWidth) {
	                jQuery(this).width(priceWidth);
	            }
	        })
	    }
	},

    pdfForm:
	{
	    init: function() {
	        jQuery('input.clearFields').click(function() {
	            jQuery('.pdfForm input[type="text"]').val('');
	            return false;
	        })
	    },

	    clearForm: function() {
	        jQuery('input.brochureField').each(function() {
	            this.value = '';
	        });

	        jQuery('span.brochureCheckBox input').each(function() {
	            this.checked = false;
	        });

	        ResetValidators();
	    }
	},

    routeBookingForm:
	{
	    init: function() {
	        jQuery('.vehicleTypes input').click(function() {
	            if (FireTypeOfVehicleValidation != 'undefined') {
	                FireTypeOfVehicleValidation();
	            }
	        });
	    },

	    initFormClearing: function() {
	        var clearMessageText = jQuery('span[id=clearMessageText]').text();
	        var clearMessageTitle = jQuery('span[id=clearMessageTitle]').text();
	        jAlert(clearMessageText, clearMessageTitle, function(r) { Scandlines.routeBookingForm.clearForm(); });
	    },

	    clearForm: function() {
	        jQuery('input.routeBookingField').each(function() {
	            this.value = '';
	        });

	        jQuery('textarea.routeBookingField').each(function() {
	            this.value = '';
	        });

	        jQuery('span.routeBookingCheckBox input').each(function() {
	            this.checked = false;
	        });

	        jQuery('.vehicleTypes input').each(function() {
	            this.checked = false;
	        });

	        jQuery('select.routeBookingSelect').each(function() {
	            this.selectedIndex = 0;
	        });

	        ResetValidators();
	    }
	},

    //init timepicker
    timepicker:
    {
        init: function() {
            jQuery('.timeField').timePicker();
        },
        updateTimeField: function(sourceInput) {
            Scandlines.timepicker.updateTime(sourceInput);

            //callValidators here

        },
        updateTime: function(sourceInput) {
            sourceInput.parent().find('input.txt').val(sourceInput.val());
        }

    },
    //init datepicker
    datepicker:
	{
	    init: function() {
	        var lang = GetCurrentLanguage();

	        switch (lang.toLowerCase()) {
	            case 'en':
	                {
	                    jQuery.datepicker.setDefaults({ dayNamesMin: ['Mo', 'Tu', 'We', 'Th', 'Fr', 'Sa', 'Su'],
	                        monthNames: ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']
	                    });
	                    break;
	                }
	            case 'da':
	            case 'da-dk':
	                {
	                    jQuery.datepicker.setDefaults({ dayNamesMin: ['Ma', 'Ti', 'On', 'To', 'Fr', 'Lø', 'Sø'],
	                        monthNames: ['Januar', 'Februar', 'Marts', 'April', 'Maj', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'December']
	                    });
	                    break;
	                }
	            case 'de':
	            case 'de-de':
	                {
	                    jQuery.datepicker.setDefaults({ dayNamesMin: ['Mo', 'Di', 'Mi', 'Do', 'Fr', 'Sa', 'So'],
	                        monthNames: ['Januar', 'Februar', 'März', 'April', 'Mai', 'Juni', 'Juli', 'August', 'September', 'Oktober', 'November', 'Dezember']
	                    });
	                    break;
	                }
	        }

	        if (!jQuery('input.fullRange') || !jQuery('input.fullRange').length) {
	            jQuery.datepicker.setDefaults({ minDate: "0" });
	        }
	        else {
	            jQuery.datepicker.setDefaults({ changeMonth: true, changeYear: true, yearRange: '-70:+10' });
	        }

	        jQuery(".dateField").datepicker({ dateFormat: 'dd.mm.yy', onSelect: function() { } });

	        //jQuery(".dateField fullRange").datepicker({ dateFormat: 'dd.mm.yy', onSelect: function() { } });
	    }
	},

    links:
	{
	    init: function() {
	        jQuery('a[rel="external"]').click(function() {
	            window.open(jQuery(this).attr('href'));
	            return false;
	        });
	    }
	},

    autobizz:
	{
	    init: function() {
	        jQuery('ul.doubleField input[type="text"]').keydown(function(e) {
	            if (jQuery(this).hasClass('short')) {
	                if ((((jQuery(this).val().length) + 1) > jQuery(this).attr('maxlength')) && !isEditKey(e.which)) {
	                    jQuery(this).parents('.doubleField').find('input[class!="short"]').focus();
	                }
	            }
	        });
	    }

	},
    pbs:
	{
	    init: function() {
	        if (jQuery('span.showPbs').find('input').is(':checked')) {
	            jQuery('#pbs').slideDown("slow");
	        }

	        jQuery('span.showPbs').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#pbs').slideDown("slow");
	            }
	        });
	        jQuery('span.hidePbs').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#pbs').slideUp("slow");
	            }
	        });


	    }
	},

    card:
	{
	    init: function() {
	        if (jQuery('span.showOrderScandlinesCard').find('input').is(':checked')) {
	            jQuery('#orderScandlinesCard').slideDown("slow");
	        }

	        jQuery('span.showOrderScandlinesCard').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#orderScandlinesCard').slideDown("slow", function() {
	                });
	            }
	        });
	        jQuery('span.hideOrderScandlinesCard').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#orderScandlinesCard').slideUp("slow", function() {
	                });
	            }
	        });

	        jQuery('a.addExtraCard').click(function() {
	            if (!jQuery('#addExtraCard').is(':visible')) {
	                jQuery('#addExtraCard').slideDown("slow", function() {
	                });
	            }
	            return false;
	        });
	        jQuery('a.removeExtraCard').click(function() {
	            jConfirm('Kortet og de oplysninger, du har skrevet slettes fra aftalen', 'Slet kort og indtastede informationer?',
							function(r) {
							    if (r) {
							        jQuery('#addExtraCard').slideUp("slow", function() {
							        });
							    }
							}
						);
	            return false;
	        });
	    }
	},
    brobizz:
	{
	    init: function() {
	        if (jQuery('span.showBrobizz').find('input').is(':checked')) {
	            jQuery('#brobizz').slideDown("slow", function() {
	            });
	        }
	        jQuery('span.showBrobizz').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#brobizz').slideDown("slow", function() {
	                });
	            }
	        });
	        jQuery('span.hideBrobizz').find('input').click(function() {
	            if (jQuery(this).is(':checked')) {
	                jQuery('#brobizz').slideUp("slow", function() {
	                });
	            }
	        });

	    }
	},

    map:
	{
	    routesAmount: 8,
	    currentRoute: 2,
	    changeInterval: 4000,
	    init: function(sign) {
	        if (sign == 'frontpage') {
	            jQuery('.route div').css({ opacity: '0' });
	            jQuery('#route1 div').css({ opacity: '1' });
	            setInterval('Scandlines.map.nextRoute()', Scandlines.map.changeInterval);
	        }
	        else {
	            $('.routeOverviewMap area').hover(function() {
	                routeId = $(this).attr('class');
	                if (routeId != $('.route:visible').attr('id')) {
	                    $('.route').hide('fast');
	                    $('#' + routeId).show('fast');
	                }
	                return false;
	            });
	        }
	    },
	    nextRoute: function() {
	        jQuery('.route div').animate({ opacity: '0' }, 'slow');
	        jQuery('#route' + Scandlines.map.currentRoute + ' div').animate({ opacity: '1' }, "slow");
	        Scandlines.map.currentRoute++;
	        if (Scandlines.map.currentRoute > Scandlines.map.routesAmount) {
	            Scandlines.map.currentRoute = 1;
	        }
	    }
	},

    footer:
    {

        setFooter: function() {
            var footer = jQuery('#footer');
            var wrapper = jQuery('#wrapper');

            var footerHeight = footer.height();

            wrapper.css('padding-bottom', footerHeight);
        }
    },
    //product offers in the rotating box
    productOffers:
	{
	    itemWidth: 452, //width of block with offer
	    showInterval: 6000, //time of showing for each item (ms)
	    itemAmount: 0, //how many items in the rotating block (items + 1)
	    currentItem: 0,
	    list: null,
	    listItem: null,
	    fadeEffectLayer: null,
	    prepare: function() {
	        list = jQuery('#rotatingOfferBox ul');
	        listItem = jQuery('#rotatingOfferBox ul li');
	        fadeEffectLayer = jQuery('#effectLayer');

	        fadeEffectLayer.hide();

	        listWidth = listItem.length * Scandlines.productOffers.itemWidth;
	        Scandlines.productOffers.itemAmount = listItem.length;
	        list.width(listWidth);
	        listItem.show();
	        setInterval('Scandlines.productOffers.rotating()', Scandlines.productOffers.showInterval);
	    },
	    rotating: function() {
	        fadeEffectLayer.fadeIn('slow', function() {
	            list.css('left', '-' + (Scandlines.productOffers.currentItem * Scandlines.productOffers.itemWidth) + 'px');
	        });

	        jQuery('#rotatingOfferBox ul li a.toProductPage').removeClass('active');

	        if (Scandlines.productOffers.currentItem == Scandlines.productOffers.itemAmount - 1) {
	            jQuery(listItem.eq(0)).find('a.toProductPage').addClass("active");
	        }
	        else {
	            jQuery(listItem.eq(Scandlines.productOffers.currentItem + 1)).find('a.toProductPage').addClass("active");
	        }

	        fadeEffectLayer.fadeOut('slow');

	        Scandlines.productOffers.currentItem++;
	        if (Scandlines.productOffers.currentItem == Scandlines.productOffers.itemAmount) {
	            Scandlines.productOffers.currentItem = 0;
	        }

	    }
	},
    categoryDetails:
	{
	    currencyCookieKey: "currency",

	    init: function() {
	        jQuery('.optionsPanel select').change(function() {
	            var currency = jQuery('.optionsPanel select option:selected').val();
	            Scandlines.categoryDetails.switchCurrency(currency);
	            return false;
	        });
	    },

	    //new implementation of show all required: show all offers despite of preorder available option	
	    showAll: function(link) {
	        jQuery('.optionsPanel .showAll').addClass('active');
	    },
	    showOffers: function(link) {
	        jQuery('.optionsPanel .showOffers').addClass('active');
	    },

	    //optimization
	    switchCurrency: function(currencyToSwitch) {
	        if (currencyToSwitch == 'euro') {
	            createCookie(Scandlines.categoryDetails.currencyCookieKey, 'euro');
	            jQuery('span.dkkProductPrice').removeClass('active');
	        }
	        else {
	            jQuery('span.euroProductPrice').removeClass('active');
	            createCookie(Scandlines.categoryDetails.currencyCookieKey, 'dkk');
	        }

	        jQuery('span.' + currencyToSwitch + 'ProductPrice').addClass('active');
	    }
	},

    expandedCategoryCookie:
	{
	    cookieKey: 'expandednSubCategories',

	    add: function(section) {
	        var expandedSections = readCookie(Scandlines.expandedCategoryCookie.cookieKey);
	        if (expandedSections && expandedSections.indexOf(section.attr('id')) != -1) {
	            return;
	        }

	        if (!expandedSections) {
	            expandedSections = '|' + section.attr('id');
	        }
	        else {
	            expandedSections += '|' + section.attr('id');
	        }
	        createCookie(Scandlines.expandedCategoryCookie.cookieKey, expandedSections);
	    },

	    remove: function(section) {
	        var expandedSections = readCookie(Scandlines.expandedCategoryCookie.cookieKey);
	        if (expandedSections) {
	            expandedSections = expandedSections.replace('|' + section.attr('id'), '');
	            createCookie(Scandlines.expandedCategoryCookie.cookieKey, expandedSections);
	        }
	    },

	    expand: function() {
	        var expandedSections = readCookie(Scandlines.expandedCategoryCookie.cookieKey);
	        if (expandedSections) {
	            var ids = expandedSections.split('|');
	            for (var i = 0; i < ids.length; i++) {
	                if (ids[i] && ids[i] != 'null') {
	                    jQuery("li[id=" + ids[i] + "]").each(function() {
	                        jQuery(this).find('h4 a').click();
	                    });
	                }
	            }
	        }
	    }


	},

    quickPoll:
	{
	    fixGroupNames: function() {
	        jQuery('.vote input[type="radio"]').each(function() {
	            jQuery(this).attr('name', function() { return 'PollVote'; });
	            jQuery(this).removeAttr('checked');
	        });
	        jQuery('.vote input[type="radio"]:first').click();
	    },

	    addClickHandlers: function() {
	        jQuery("input[id*='uiHfSelectedOptionID']").attr('value', jQuery('.vote input[type="radio"]:first').next('input').attr('value'));

	        jQuery('.vote input[type="radio"]').click(function() {
	            jQuery("input[id*='uiHfSelectedOptionID']").attr('value', jQuery(this).next('input').attr('value'));
	        });
	    }
	}

}

jQuery(document).ready(function() {

	Scandlines.init();

});


//creates browser cookie
function createCookie(name, value, minutes) {
	if (minutes) {
		var date = new Date();
		date.setTime(date.getTime() + (minutes * 60 * 1000));
		var expires = "; expires=" + date.toGMTString();
	}
	else {
		var expires = "";
	}
	document.cookie = name + "=" + value + expires + "; path=/";
}

//read browser cookies
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for (var i = 0; i < ca.length; i++) {
		var c = ca[i];
		while (c.charAt(0) == ' ') c = c.substring(1, c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
	}
	return null;
}

//check functions
function isInteger (s)
{
	var i;

	if (isEmpty(s))
	if (isInteger.arguments.length == 1) return 0;
	else return (isInteger.arguments[1] == true);

	for (i = 0; i < s.length; i++)
	{
		var c = s.charAt(i);

		if (!isDigit(c)) return false;
	}

	return true;
}

function isEmpty(s)
{
	return ((s == null) || (s.length == 0))
}

function isDigit (c)
{
	return ((c >= "0") && (c <= "9"))
}

function isEditKey (keyCode)
{
	// ←, ↑, →, ↓, tab, del, backspace keys are allowed
	if((keyCode >= 8) && (keyCode <=46))
	{
		if((keyCode == 8) || (keyCode == 46) || (keyCode == 9) || ((keyCode > 36) && (keyCode < 41)))
		{
			return true;
		}
	}
	return false;
}

function limitChars(text, limit)
{
	var textValue = text.val();	
	var textLength = textValue.length;
	
	//count new line and carriage return
	var enterAmount = 0;
	for(var i = 0; i < textLength; i++)
	{
	    if(textValue.charCodeAt(i) == 10 || textValue.charCodeAt(i) == 13)
	    {
	        enterAmount++;
	    }
	}
	
	textLength += enterAmount;
				
	if (textLength > limit)
	{
		text.val(textValue.substr(0, limit - enterAmount));
		
		return false;
	}
		
	return true;
}

function GetCurrentLanguage() {
    var queryLanguageParameter = 'sc_lang=';
    var cookieLanguageParameter = '#lang=';

    var siteDomain = location.hostname;
    var domainZone = siteDomain.substr(siteDomain.lastIndexOf('.') + 1);
    var defaultLanguages = {'dk':'da-DK', 'de':'de-DE', 'com':'en'};
    
    if (self.location.href.indexOf('sc_lang=') > 0)
    {
        var startIndex = self.location.href.indexOf(queryLanguageParameter) + queryLanguageParameter.length;
        var endIndex;

        if (self.location.href.indexOf('&', startIndex) > 0)
        {
            endIndex = self.location.href.indexOf('&', startIndex);
        }
        else
        {
            endIndex = startIndex + self.location.href.length - startIndex;
        }
        return self.location.href.substring(startIndex, endIndex);
    }
    else if (document.cookie)
    {
        var match = document.cookie.match(/(bordershop|scandlinesdk|scandlinesde)#lang=(en|da-DK|de-DE)/);
        if (match)
        {
            return match[2];
        }

        return 'da-DK';
    }
    else
    {
        return defaultLanguages[domainZone];
    }

}

function ResetValidators() {
    if (typeof (Page_Validators) != 'undefined') {
        for (var i = 0; i < Page_Validators.length; i++) {
            if (Page_Validators[i]) {
                var jQueryValidator = jQuery(Page_Validators[i]);
                jQueryValidator.hide();
                jQueryValidator.parents('.error').removeClass('error');
            }
        }
    }
}