﻿
var LangOpen = false;
var PEEPDomain = '';
var FTSDefaultValue = '';
var lang = 'en';
var DLANG = new Array();

// English
DLANG['en'] = new Array();
DLANG['en']['close'] = 'Close';
DLANG['en']['locally'] = 'locally';
DLANG['en']['all_makes'] = 'All makes';
DLANG['en']['all_models'] = 'All models';
DLANG['en']['all_body_types'] = 'All body types';
DLANG['en']['in_europe'] = 'in Europe';
DLANG['en']['days'] = 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday';
DLANG['en']['months'] = 'January,February,March,April,May,June,July,August,September,October,November,December';

// German
DLANG['de'] = new Array();
DLANG['de']['close'] = 'schliessen';
DLANG['de']['locally'] = 'örtlich';
DLANG['de']['all_makes'] = 'All makes';
DLANG['de']['all_models'] = 'Alle modelle';
DLANG['de']['all_body_types'] = 'All body types';
DLANG['de']['in_europe'] = 'in Europa';
DLANG['de']['days'] = 'Sonntag,Montag,Dienstag,Mittwoch,Donnerstag,Freitag,Samstag';
DLANG['de']['months'] = 'Januar,Februar,März,April,Mai,Juni,Juli,August,September,Oktober,November,Dezember';

// Spanish
DLANG['es'] = new Array();
DLANG['es']['close'] = 'Cerrar';
DLANG['es']['locally'] = 'locally';
DLANG['es']['all_makes'] = 'All makes';
DLANG['es']['all_models'] = 'All Models';
DLANG['es']['all_body_types'] = 'All body types';
DLANG['es']['in_europe'] = 'in Europe';
DLANG['es']['days'] = 'Domingo,Lunes,Martes,Mi&#233;rcoles,Jueves,Viernes,S&#225;bado';
DLANG['es']['months'] = 'enero,febrero,marcha,abril,mayo,junio,julio,agosto,septiembre,octubre,noviembre,diciembre';

// French
DLANG['fr'] = new Array();
DLANG['fr']['close'] = 'Fermer';
DLANG['fr']['locally'] = 'locally';
DLANG['fr']['all_makes'] = 'All makes';
DLANG['fr']['all_models'] = 'All Models';
DLANG['fr']['all_body_types'] = 'All body types';
DLANG['fr']['in_europe'] = 'in Europe';
DLANG['fr']['days'] = 'Dimanche,Lundi,Mardi,Mercredi,Jeudi,Vendredi,Samedi';
DLANG['fr']['months'] = 'janvier,f&eacute;vrier,mars,avril,mai,juin,juillet,ao&ucirc;t,septembre,octobre,novembre,d&eacute;cembre';

// Italian
DLANG['it'] = new Array();
DLANG['it']['close'] = 'Chiudere';
DLANG['it']['locally'] = 'locally';
DLANG['it']['all_makes'] = 'All makes';
DLANG['it']['all_models'] = 'All Models';
DLANG['it']['all_body_types'] = 'All body types';
DLANG['it']['in_europe'] = 'in Europe';
DLANG['it']['days'] = 'domenica,lunedì,martedì,mercoledì,giovedì,venerdì,sabato';
DLANG['it']['months'] = 'gennaio,febbraio,marzo,aprile,maggio,giugno,luglio,agosto,settembre,ottobre,novembre,dicembre';

// Polish
DLANG['pl'] = new Array();
DLANG['pl']['close'] = 'Zamknij';
DLANG['pl']['locally'] = 'locally';
DLANG['pl']['all_makes'] = 'All makes';
DLANG['pl']['all_models'] = 'All Models';
DLANG['pl']['all_body_types'] = 'All body types';
DLANG['pl']['in_europe'] = 'in Europe';
DLANG['pl']['days'] = 'niedziela,poniedzia&#322;ek,wtorek,&#347;roda,czwartek,pi&#261;tek,sobota';
DLANG['pl']['months'] = 'stycze&#324;,luty,marzec,kwiecie&#324;,maj,czerwiec,lipiec,sierpie&#324;,wrzesie&#324;,pa&#378;dziernik,listopad,grudzie&#324;';

// Russian
DLANG['ru'] = new Array();
DLANG['ru']['close'] = 'Close';
DLANG['ru']['locally'] = 'locally';
DLANG['ru']['all_makes'] = 'All makes';
DLANG['ru']['all_models'] = 'All Models';
DLANG['ru']['all_body_types'] = 'All body types';
DLANG['ru']['in_europe'] = 'in Europe';
DLANG['ru']['days'] = 'Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота';
DLANG['ru']['months'] = 'Январь,Февраль,Март,Апрель,Май,Июнь,Июль,Август,Сентябрь,Октябрь,Ноябрь,Декабрь';

// Portuguese
DLANG['pt'] = new Array();
DLANG['pt'] = 'Fechar';
DLANG['pt']['locally'] = 'locally';
DLANG['pt']['all_makes'] = 'All makes';
DLANG['pt']['all_models'] = 'All Models';
DLANG['pt']['all_body_types'] = 'All body types';
DLANG['pt']['in_europe'] = 'in Europe';
DLANG['pt']['days'] = 'Domingo,Segunda,Ter&#231;a,Quarta,Quinta,Sexta,S&#225;bado';
DLANG['pt']['months'] = 'Janeiro,Fevereiro,Mar&#231;o,Abril,Maio,Junho,Julho,Agosto,Setembro,Outubro,Novembro,Dezembro';

function buildPage(domain, language)
{
    // Set the global Domain
    PEEPDomain = domain;
	
	// Set the global language
	lang = language;

    // Attach all events
    attachEvents();

    // Convert Objects to IFrames
    convertObjectToIFrame();

    // Initialise the contact modal
    contactModal.init();
	
	// Show the date
    document.getElementById('dateLabel').innerHTML = getDate();
}

function xBidDrop()
{
	if ( document.getElementById('xBidLink') && document.getElementById('xBidDropPanel') )
	{
		$('#xBidLink').mouseover(function () {
			$('#xBidDropPanel').css('left', (($(window).width() / 2) + 76 ));
		});
		
		$(document).click(function(e){
			$('#xBidDropPanel').css('left', -9999);
		});
	}
}

function attachEvents()
{
    // FTS
    if (document.getElementById('fts_input') && document.getElementById('fts_submit')) {
        var i = document.getElementById('fts_input');
        var s = document.getElementById('fts_submit');

        FTSDefaultValue = i.value

        i.onfocus = function () { if (this.value == FTSDefaultValue) this.value = ''; }
        i.onblur = function () { if (this.value == '') this.value = FTSDefaultValue; }
        s.onclick = function () {
            if (document.getElementById('fts_input').value != FTSDefaultValue) {
                var f = document.getElementById('aspnetForm');
                var v = document.getElementById('fts_input').value;
                v = v.replace(/^(\s+)/, ''); // Remove any preceding spaces
                v = v.replace(/(\s+)$/, ''); // Remove any trailing spaces
                f.method = 'GET';
                f.action = PEEPDomain + '/SearchVehicle/AutoVehicleSearch'; //?freetext=' + escape(v);
            }
        }
        i.onkeydown = function (e) {
            var evt = e || window.event;
            if (evt.keyCode == 13) {
                var f = document.getElementById('aspnetForm');
                var v = this.value;
                v = v.replace(/^(\s+)/, ''); // Remove any preceding spaces
                v = v.replace(/(\s+)$/, ''); // Remove any trailing spaces
                f.method = 'GET';
                f.action = PEEPDomain + '/SearchVehicle/AutoVehicleSearch'; //?freetext=' + escape(v);
                f.submit();
            }
        }
    }
}

function convertObjectToIFrame() {
    var o = document.getElementsByTagName('object');
    if (o.length > 0) {
        for (var i = 0; i < o.length; i++) {
            if (o[i].type && (o[i].type == 'text/html') && o[i].data) {
                var frame = '<iframe id="ObjectIFrame' + i + '" scrolling="auto" frameborder="0" marginwidth="0" marginheight="0" border="0"';
                if (o[i].style['cssText']) { frame += ' style="' + o[i].style['cssText'] + '"'; }
                frame += ' src="' + o[i].data + '">Please update your browser.</iframe>';
                var d = document.createElement('div');
                d.innerHTML = frame;
                o[i].parentNode.insertBefore(d, o[i]);
                o[i].style.display = 'none';
            }
        }
    }
}

// If on shared domain - hook into PEEP close button after completion
function toggleModalPopup(w) { contactModal.close(); }

// Self contained object to work with PEEP contact modal
var contactModal = {
    _background: undefined,
    _modal: undefined,
    _iframe: undefined,
    init: function () {
        if (document.getElementById('contactmodal')) {
		
			var preIE8 = ( (navigator.appVersion.indexOf("MSIE") != -1) &&
				( parseFloat(navigator.appVersion.split("MSIE")[1]) < 8 ));
				
            // Build the required elements
            _background = document.createElement('div');
			if ( preIE8 )
			{
				_background.setAttribute('className', 'ModalBackground');
			}
			else
			{
				_background.setAttribute('class', 'ModalBackground');
			}
            _modal = document.createElement('div');
			if ( preIE8 )
			{
				_modal.setAttribute('className', 'ModalPopup');
			}
			else
			{
				_modal.setAttribute('class', 'ModalPopup');
			}
            var link = document.createElement('a');
            link.appendChild(document.createTextNode(DLANG[lang]['close']));
            link.onclick = function () { contactModal.close(); }
            var close = document.createElement('div');
			if ( preIE8 )
			{
				close.setAttribute('className', 'Close');
			}
			else
			{
				close.setAttribute('class', 'Close');
			}
            var inner = document.createElement('div');
			if ( preIE8 )
			{
				inner.setAttribute('className', 'Inner');
			}
			else
			{
				inner.setAttribute('class', 'Inner');
			}
            var content = document.createElement('div');
			if ( preIE8 )
			{
				content.setAttribute('className', 'ModalContent');
			}
			else
			{
				content.setAttribute('class', 'ModalContent');
			}
            _iframe = document.createElement('iframe');
            _iframe.scrolling = 'no';
            _iframe.src = 'javascript:false;';
            _iframe.id = 'ContactUsFrame';
            _iframe.frameBorder = 0;

            // Build the DOM            
            inner.appendChild(link);
            close.appendChild(inner);
            _modal.appendChild(close);
            content.appendChild(_iframe);
            _modal.appendChild(content);
            document.getElementsByTagName('body')[0].appendChild(_modal);
            document.getElementsByTagName('body')[0].appendChild(_background);

            // Attach the click event to the button
            document.getElementById('contactmodal').onclick = function () { contactModal.open(); }
        }
    },
    open: function () {
        // Open the page in the iframe
        _iframe.src = PEEPDomain + '/ContactUs';

        // Show the modal
        _modal.style.height = 'auto';
        _modal.style.overflow = 'auto';

        // Move everything
        this.move();

        // Attach the window re-size event
        window.onresize = function () { contactModal.move(); }
    },
    move: function () {
        // Get the browser info
        var browser = this.getBrowserSize();
        var scroll = this.getBodyScroll();

        // Reposition and show the background
        _background.style.width = browser.w + 'px';
        _background.style.height = browser.h + 'px';
        _background.style.top = scroll.y + 'px';
        _background.style.left = scroll.x + 'px';

        // Reposition the modal
        _modal.style.top = (browser.h / 2) - (_modal.offsetHeight / 2) + 'px';
        _modal.style.left = (browser.w / 2) - (_modal.offsetWidth / 2) + 'px';
    },
    close: function () {
        // Reposition and show the background
        _background.style.width = '1px';
        _background.style.height = '1px';
        _background.style.top = '-1px';
        _background.style.left = '-1px';

        // Reposition and show the modal
        _modal.style.height = '1px';
        _modal.style.overflow = 'hidden';
        _modal.style.top = '-1px';
        _modal.style.left = '0';

        // Remove the event - could be better?
        window.onresize = null;
    },
    getBodyScroll: function () {
        var x = window.pageXOffset ||
            document.body.scrollLeft ||
            document.documentElement.scrollLeft;

        var y = window.pageYOffset ||
            document.body.scrollTop ||
            document.documentElement.scrollTop;

        return { x: (x ? x : 0), y: (y ? y : 0) };
    },
    getBrowserSize: function () {
        var w = document.documentElement.clientWidth;
        var h = document.documentElement.clientHeight;
        return { w: (w ? w : 0), h: (h ? h : 0) };
    }
}

function getDate()
{
    var d = new Date();
    // var wday = DLANG[lang]['days'].split(',')[d.getDay()];
    var lmonth = DLANG[lang]['months'].split(',')[d.getMonth()];
    var day = ( d.getDate() < 10 )? '0' + d.getDate() : d.getDate();
    var hours = ( d.getHours() < 10 )? '0' + d.getHours() : d.getHours();
    var minutes = ( d.getMinutes() < 10 )? '0' + d.getMinutes() : d.getMinutes();
    return day + ' ' + lmonth + ' ' + hours + ':' + minutes;
}

/* Homepage functions */

// On select Manufacturer
function selectMake()
{
	// Empty the model select and show 'all models'
	$('select#model-chooser').empty();
	$('select#model-chooser').append($('<option>', { 'value': '', 'selected': 'selected' }).text( DLANG[lang]['all_models'] ));
	$('select#model-chooser').selectmenu('disable');

	// Get the selected make
	var make = $('select#make-chooser').selectmenu('value');
	
	// Get the vehicle data from PEEP
	$.getJSON( '/peepcall/Search/Vehicle/Make/' + make, function (data) {

		// Whizz through the models
		$.each(data.ModelGroups, function (i, model) {
			$('select#model-chooser').append($('<option>', { 'value': data.BaseModelGroups[i] }).text(model));
		});

		// Update the select menu
		$('select#model-chooser').selectmenu();

		// Update the buttons
		updateQuickSearchButtons( data );
	});
}

// On select Model
function selectModel()
{
	// Get the selected make
	var make = $('select#make-chooser').selectmenu('value');
	var model = $('select#model-chooser').selectmenu('value');

	// If they've selected 'show all'
	if ( model == '' )
	{
		// Re-select the make
		selectMake( make );
	}
	else
	{
		// Get the vehicle data from PEEP
		$.getJSON( '/peepcall/Search/Vehicle/Make/' + make + '/' + model, function (data) {

			// Update the buttons
			updateQuickSearchButtons( data );
		});
	}
}

function updateQuickSearchButtons( data )
{
	// Update the button counts
	//$('div#count-car-local a').text(data.VehicleCountLocal + ' ' + DLANG[lang]['locally'] );
	//$('div#count-car-europe a').text(data.VehicleCountEurope + ' ' + DLANG[lang]['in_europe'] );
	
	// Local button disable
	if (( data.VehicleCountLocal == 0 ) && !$('div#count-car-local').hasClass('Disabled') )
	{
		$('div#count-car-local').addClass('Disabled');
	}
	else if ( ( data.VehicleCountLocal > 0 ) && $('div#count-car-local').hasClass('Disabled') )
	{
		// Remove the class
		$('div#count-car-local').removeClass('Disabled');
	}
	
	// Europe button disable
	if (( data.VehicleCountEurope == 0 ) && !$('div#count-car-europe').hasClass('Disabled') )
	{
		$('div#count-car-europe').addClass('Disabled');
	}
	else if ( ( data.VehicleCountEurope > 0 ) && $('div#count-car-europe').hasClass('Disabled') )
	{
		$('div#count-car-europe').removeClass('Disabled');
	}
}

function mycarousel_initCallback(carousel)
{
	// Pause autoscrolling if the user moves with the cursor over the clip.
	carousel.clip.hover(function () {
		carousel.stopAuto();
	}, function () {
		carousel.startAuto();
	});
}

function quickSearch( type, location )
{
	// Setup the vars
	var url = PEEPDomain;
	var make = $('select#make-chooser').selectmenu('value');
	var model = $('select#model-chooser').selectmenu('value');
	
	// Build the URL
	if ( type == 'car' ){ url += '/VehicleSearchResults?'; }
	if ( location == 'de' ){ url += 'countryCode=DE&'; }
	if ( make != '' ){ url += 'make=' + make + '&'; }
	if ( model != '' ){ url += 'ModelGroup=' + model + '&'; }
	
	// Do the re-direct
	window.location = url;
}

// 
var HGV = {
    _initialised: false,
    init: function () {
		if ( !this._initialised )
		{
			// Attach the button 
			$('a#count-hgv-local').click(function () {
				HGV.search('de');
				return false;
			});
			$('a#count-hgv-europe').click(function () {
				HGV.search('eu');
				return false;
			});
			
			// Convert the Body Type select to html friendly
			$('select#hgv-body-chooser').selectmenu({
				style: 'dropdown',
				select: function (event, options) { HGV.selectBody(); }
			});
			$('select#hgv-body-chooser').selectmenu('disable');
			
			// Convert the Make select to html friendly
			$('select#hgv-make-chooser').selectmenu({
				style: 'dropdown',
				select: function (event, options) { HGV.selectMake(); }
			});
			$('select#hgv-make-chooser').selectmenu('disable');
			
			// Get the body type data from PEEP
			$.getJSON( '/peepcall/Search/HeavyGoodsVehicle/BodyType', function (data) {

				// Empty the select and show 'all body types'
				$('select#hgv-body-chooser').empty();
				$('select#hgv-body-chooser').append($('<option>', { 'value': '', 'selected': 'selected' }).text( DLANG[lang]['all_body_types'] ));
	
				// Whizz through the models
				$.each(data.BodyTypes, function (i, bodyType) {
					$('select#hgv-body-chooser').append($('<option>', { 'value': data.BaseBodyTypes[i] }).text(bodyType));
				});

				// Update the select menu
				$('select#hgv-body-chooser').selectmenu();

				// Update the button counts
				$('a#count-hgv-local').text(data.VehicleCountLocal + ' ' + DLANG[lang]['locally'] );
				$('a#count-hgv-europe').text(data.VehicleCountEurope + ' ' + DLANG[lang]['in_europe'] );
			});
			
			
			// Flag as loaded
			this._initialised = true;
		}
	},
	selectBody: function ()
	{
		// Get the selected body type
		var bodyType = $('select#hgv-body-chooser').selectmenu('value');

		// Get the model data from PEEP
		$.getJSON( '/peepcall/Search/HeavyGoodsVehicle/BodyType/' + bodyType, function (data) {

			// Empty the select and show 'all make types'
			$('select#hgv-make-chooser').empty();
			$('select#hgv-make-chooser').append($('<option>', { 'value': '', 'selected': 'selected' }).text( DLANG[lang]['all_makes'] ));

			// Whizz through the models
			$.each(data.Makes, function (i, make) {
				$('select#hgv-make-chooser').append($('<option>', { 'value': make }).text(make));
			});

			// Update the select menu
			$('select#hgv-make-chooser').selectmenu();

			// Update the button counts
			$('a#count-hgv-local').text(data.VehicleCountLocal + ' ' + DLANG[lang]['locally'] );
			$('a#count-hgv-europe').text(data.VehicleCountEurope + ' ' + DLANG[lang]['in_europe'] );
		});
	},
	selectMake: function ()
	{
		// Get the selected make
		var bodyType = $('select#hgv-body-chooser').selectmenu('value');
		var make = $('select#hgv-make-chooser').selectmenu('value');

		// If they've selected 'show all'
		if ( make == '' )
		{
			// Re-select the body type
			HGV.selectBody();
		}
		else
		{
			// Get the vehicle data from PEEP
			$.getJSON( '/peepcall/Search/HeavyGoodsVehicle/BodyType/' + bodyType + '/' + make, function (data) {

				// Update the button counts
				$('a#count-hgv-local').text(data.VehicleCountLocal + ' ' + DLANG[lang]['locally'] );
				$('a#count-hgv-europe').text(data.VehicleCountEurope + ' ' + DLANG[lang]['in_europe'] );
			});
		}
	},
	search: function ( location )
	{
		// Setup the vars
		var bodyType = $('select#hgv-body-chooser').selectmenu('value');
		var make = $('select#hgv-make-chooser').selectmenu('value');
		
		// Build the URL
		var url = PEEPDomain + '/VehicleSearchResults?';
		if ( location == 'de' ){ url += 'countryCode=DE&'; }
		if ( bodyType != '' ){ url += 'bodyType=' + bodyType + '&'; }
		if ( make != '' ){ url += 'make=' + make + '&'; }
		
		// Do the re-direct
		window.location = url;
	}
}



