/*!
*  motors-generic-lib.js
*/

/* setup the motors objects (and prevent a load of errors!) */

if (typeof motors == 'undefined') { motors = {}; }
if (typeof motors.error == 'undefined') { motors.error = {}; }
if (typeof motors.utils == 'undefined') { motors.utils = {}; }
if (typeof motors.filter == 'undefined') { motors.filter = {}; }
if (typeof motors.search == 'undefined') { motors.search = {}; }
if (typeof motors.navigators == 'undefined') { motors.navigators = {}; }

rotatorContent = {};

/*
*   parse the query string as a json object and chuck it into the motors obj
*/

motors.queryString = (function (window) {
    var queryArr = window.location.search.substr(1).split('&'),
        queryObj = {},
        temp;
    for (var i in queryArr) {
        if (queryArr.hasOwnProperty(i)) {
            temp = queryArr[i].split('=');
            queryObj[temp[0]] = temp[1];
        }
    }
    return queryObj;
})(this);

/*
*  get/set cookie
*/

//loads MPU if id exists
function loadMPU() {
    var elem = document.getElementById('mpuPop');
    if (elem != null) {
        elem.innerHTML = "";
        eval('dapMgr.renderAd("mpuPop", "&amp;PG=UKMGM2&amp;AP=1089", 300, 250);');
    }
}

//sets hidden field with dealerID selected value(clicked on etc) so we can acces it for other functions
function setDealerID(id) {
    var hidden = document.getElementById('tmpDealerID');
    if (hidden) {
        hidden.value = id;
    }
}

//show or hide pop up in the middle of the screen
function showPopMiddle(id, typeclass) {    
    
    //JQuery center funcion
    jQuery.fn.center = function () {
        this.css("position", "absolute");
        this.css("top", (($(window).height() - this.outerHeight()) / 2) + $(window).scrollTop() + "px");
        this.css("left", (($(window).width() - this.outerWidth()) / 2) + $(window).scrollLeft() + "px");
        return this;
    }

    //get class name
    var el = document.getElementById(id);
    //check if object exists
    if (el != null) {
        var popclassname = el.className;

        //perform actions based on class name - display div and show in middle of the screen or change class to hide
        if (popclassname == 'ps_display_none') {
            showHideBlackout("show");
            el.className = typeclass;
            $(el).center();
            return true;
        }
        else if ((popclassname == typeclass) || (typeclass == 'close')) {
            showHideBlackout("hide");
            el.className = 'ps_display_none';
            return false;
        }
    }
}

function showHideBlackout(action) {
    var elemBlack = document.getElementById("darkenScreen");
    if (elemBlack != null) {
        if (action == "show") {
            elemBlack.className = "blackout";
        }
        else {
            elemBlack.className = "blackout ps_display_none";
        }
    }
}

//get params from Querystring
function getParameterByName(name, href) {
    name = name.replace(/[\[]/, "\\\[").replace(/[\]]/, "\\\]");
    var regexS = "[\\?&]" + name + "=([^&#]*)";
    var regex = new RegExp(regexS);
    var results = regex.exec(href);
    if (results == null)
        return "";
    else
        return decodeURIComponent(results[1].replace(/\+/g, " "));
} 

//check if valid email
function isValidEmailAddress(emailAddress) {
    var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
    return pattern.test(emailAddress);
}

function refreshMSAds() {
    /*MS Ad tags fix, MS removed function to refresh ads so had to write in emergency code to refresh on Ajax successs*/
    //checks if leaderboard is there then on success refreshes ads
    var elemAd = document.getElementById('AdTag_MotorsLeaderBoard');
    if (elemAd != null) {
        elemAd.innerHTML = "";
        dapMgr.renderAd("AdTag_MotorsLeaderBoard", "&PG=UKMGM1&AP=1390", 728, 90);
    }
    //checks if skyscarper is there then on success refreshes ads
    var elemAdSky = document.getElementById('AdTag_MotorsSkyScraper_TwoCol');
    if (elemAdSky != null) {
        elemAdSky.innerHTML = "";
        dapMgr.renderAd("AdTag_MotorsSkyScraper_TwoCol", "&PG=UKMGM3&AP=1090", 160, 600);
    }
    //checks if skyscraper and mpu is there then on success refreshes ads as mpu is on RNG sites
    var elemAdmpu = document.getElementById('mpu');
    if ((elemAdmpu != null) && (elemAdSky != null)) {
        elemAdmpu.innerHTML = "";
        dapMgr.renderAd("mpu", "&PG=UKMGM2&AP=1089", 300, 250);
    }
    /*End MS Tags*/
}

function setCookie(name, value, days, domain) {
    var date,
        expires = "";
    if (days) {
        date = new Date();
        date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
        expires = "; expires=" + date.toGMTString();
    }
    if (domain) {
        document.cookie = name + "=" + value + expires + "; path=/" + ";domain= " + domain;
    }
    else {
        document.cookie = name + "=" + value + expires + "; path=/";
    }
}

function getCookie(name) {
    var cookieArr,
            cookie,
            i = 0;
    name += "=";
    cookieArr = document.cookie.split(';');
    for (; i < cookieArr.length; i++) {
        cookie = cookieArr[i];
        while (cookie.charAt(0) === ' ') {
            cookie = cookie.substring(1, cookie.length);
        }
        if (cookie.indexOf(name) === 0) {
            return cookie.substring(name.length, cookie.length);
        }
    }
    return null;
}

/*
*  google analytics code
*/

if (typeof _gaq == 'undefined')
    var _gaq = _gaq || [];
_gaq.push(['_setAccount', '<%= GoogleAnalyticsKey %>']);
_gaq.push(['_trackPageview']);
_gaq.push(['_trackPageLoadTime']);
(function () {
    var ga = document.createElement('script'),
        s = document.getElementsByTagName('script')[0];
    ga.type = 'text/javascript';
    ga.async = true;
    ga.src = ('https:' == document.location.protocol ? 'https://ssl' : 'http://www') + '.google-analytics.com/ga.js';
    s.parentNode.insertBefore(ga, s);
})();

/*
*  set document classes
*/

(function () {
    var htmlClass = ' js';
    /*
    if (jQuery.support.cssFloat == false && (jQuery.browser.version.indexOf('7') > -1) === true) {
    htmlClass += ' ltie8 ie7';
    } else if (jQuery.support.cssFloat == false && (jQuery.browser.version.indexOf('6') > -1) === true) {
    htmlClass += ' ltie8 ie6';
    }
    */
    document.getElementsByTagName('html')[0].className += htmlClass;
})();

/*
*  round to nearest(value, round to)
*/

function toNearest(val, num) {
    return Math.round(val / num) * num
}

/*
* Omniture Event Tracking
*
* Used: in thisis (code loaded in site.master)
*
* Syntax:  omnitureEvent('Search', {'prop42': 'ryan', 'prop99': 'ryan'});
*
* Notes: fire off the Omniture tracking specifying an event type, and any modified values or additional 
* props required (need to be available to do anything). this should only be called after document.ready 
* for blatantly obvious reasons.
*
* Excessive Detail: If you are lazy you can call omnitureAuto('event1') which will try to grab the variables for the motors
* props for you from the likely candidates. Also omnitureAuto will only run on thisis pages but you 
* can call omnitureEvent whenever you like. Granted, you almost certainly shouldn't, but you could.
*
* Good news everybody! you can now append additional sub pages to the path. there is no proper logic behind 
* it atm so you would just use a string like: omnitureAuto('event1,'subPageName: anotherSubPageName: soOnAndSoForth')
*
*/

function omnitureAuto(eventTracked, subPage) {

    if (document.body.className.indexOf('thisis') < 0)
        return false;

    if (eventTracked) {
        var jsonObj = motors.constants.jsonfilter.document,
            omniObj = {},
            p42 = "", // Vehicle Make
            p43 = "", // Vehicle Model
            p44 = "", // Price Min
            p45 = "", // Price Max
            p46 = "U", // New/Used (thisis only has used cars)
            p47 = "T", // Private/Trade (default is trade)
            manuName,
            modelList,
            searchType,
            sellerType,
            i;

        if (subPage && s) {
            var page = s.pageName + ': ' + subPage,
                hier = s.hier1 + ': ' + subPage,
                p1 = s.prop1 + ': ' + subPage,
                p2 = s.prop2 + ': ' + subPage,
                p3 = s.prop3 + ': ' + subPage,
                channel = s.channel;
        }

        if (subPage == undefined || (subPage.indexOf('email') == -1 && subPage.indexOf('details') == -1)) {
            /* get make and model */
            if (jsonObj.data.manufacturer) {
                for (i = 0; i < jsonObj.data.manufacturer.item.length; i++) {
                    manuName = jsonObj.data.manufacturer.item[i].name;
                    p42 += (i > 0) ? ',' + manuName : manuName;
                    modelList = jsonObj.data.manufacturer.item[i].models.item.join(',');
                    p43 += (i > 0) ? ',' + modelList : modelList;
                }
            } else if (jsonObj.data["nav-allmakesstock"]) {
                for (i = 0; i < jsonObj.data["nav-allmakesstock"].item.length; i++) {
                    manuName = jsonObj.data["nav-allmakesstock"].item[i];
                    p42 += (i > 0) ? ',' + manuName : manuName;
                }
            } else if (jsonObj.data["nav-allmakesfranc"]) {
                for (i = 0; i < jsonObj.data["nav-allmakesfranc"].item.length; i++) {
                    manuName = jsonObj.data["nav-allmakesfranc"].item[i];
                    p42 += (i > 0) ? ',' + manuName : manuName;
                }
            }
            /* get min/max price */
            if (jsonObj.sliders !== null && jsonObj.sliders['nav-price']) {
                p44 = jsonObj.sliders['nav-price'].posStart;
                p45 = jsonObj.sliders['nav-price'].posEnd;
            }
            /* get search type */
            if (jsonObj.searchType) {
                searchType = jsonObj.searchType.toLowerCase();
                p46 = (searchType.indexOf('used') < 0) ? "N" : "U";

                sellerType = jsonObj.data['nav-vendortype'];
                if (sellerType) {
                    sellerType = sellerType.item;
                    p47 = "";
                    var privateCount = 0;
                    for (i = 0; i < sellerType.length; i++) { if (sellerType[i].indexOf('Private') > -1) { privateCount++; p47 = "P" } }
                    if (sellerType.length > privateCount) { p47 = p47 + "T"; }
                }
            }
        } else {
            // reset vars
            p46 = "";
            p47 = "";
        }

        /* build object */
        omniObj = { 'prop42': p42, 'prop43': p43, 'prop44': p44, 'prop45': p45, 'prop46': p46, 'prop47': p47 };
        if (subPage && s) {
            omniObj.pageName = page;
            omniObj.hier1 = hier;
            //omniObj['prop1'] = p1; <- doesn't need to be updated
            omniObj.prop2 = p2;
            omniObj.prop3 = p3;
            omniObj.channel = channel;
        }

        /* track event */
        omnitureEvent(eventTracked, omniObj);
    }
    return false;
}

function omnitureEvent(eventTracked, jsonObject) {
    var trackVars = "prop4,prop21,prop29,prop39,events,prop1,prop2,prop3,channel,prop42,prop43,prop44,prop45,prop46,prop47"; //don't show these on details and email pages
    s = s_gi(s_account);
    s.linkTrackEvents = (eventTracked && eventTracked !== "") ? eventTracked : "";
    s.events = s.linkTrackEvents;
    for (var kvp in jsonObject) {
        s[kvp] = jsonObject[kvp];   // deconstruct jsonObject and set key value pairs for s.prop#
        if (trackVars.indexOf(kvp) < 0) {
            trackVars += ',' + kvp; // append this value to the values list if not present
        }
    }

    s.linkTrackVars = trackVars;
    s.tl(true, 'o', s.linkTrackEvents); // [true] executes immediately, use [this] for links which inserts a 500ms delay to the event

    resetOmnitureLocation();
}

/*
*  Validate location field
*/
function checkLocation(obj) {
    var $this = (obj) ? $(obj) : $('#nav-postcode'),
        result = ($this.val() == "") ? false : true,
        newVal;

    if ($this.length == 0) return true; //don't kill new cars tab (no location field)

    if (result) {
        //remove bad characters that break the search, don't worry about any random non-alphanumeric characters they'll not break anything.
        newVal = $this.val().replace(/~|=/gi, '');
        $this.val(newVal);
        result = (newVal == "") ? false : true;
    }

    if (result) {
        $this.removeClass('empty');
        $('#validation-alert').remove();
    } else {
        $this.addClass('empty');
    }

    switchButton('#btnnav-postcode');
    toggleSliders(result);
    toggleSearchOptions(result, $this[0]);
    return result;
}

//search dealer by name
function dealerNameSearch() {
    //set elem by ID
    var elem = document.getElementById('dealer-name');  
    //if has a value then do the search as before
    if (elem != null) {
        var $main = $('#dealer-by-name'),
            $obj = $main.find('a#dealer-name_search'),
            obj = $obj[0];

        motors.filter.textbox_search(obj);
    }
}

function switchButton(obj) {
    var $obj = $(obj),
        $location = $('#nav-postcode'),
        url = $obj.attr('src'),
        newUrl = url,
        x;

    if (($obj.length == 0) || ($location.length == 0)) {
        return false;
    }

    if (url.indexOf('-grey') > 0 && $location.val() != "") {
        x = url.split('-grey');
        newUrl = x[0] + x[1];
    } else if (url.indexOf('-grey') == -1 && $location.val() == "") {
        x = url.lastIndexOf('.');
        newUrl = url.substring(0, x) + '-grey.' + url.substring((x + 1));
    }
    $obj.attr('src', newUrl);
}

/*
*  enable / disable search refinement options
*/

function toggleSearchOptions(state, obj) {
    var $input = (obj) ? obj : $('#nav-postcode')[0],
        closeMoreOpts = document.getElementById('close-more-options');

    if (state === true) {
        if (closeMoreOpts) closeMoreOpts.style.visibility = "visible";
        $('#more-options')
            .find('div.navigator-group.open')
            .show()
            .end()
            .find('ul.tabs-list')
            .removeClass('disable');
        $('div.slider')
            .slider('enable');
    } else {
        if (closeMoreOpts) closeMoreOpts.style.visibility = "hidden";
        $('#more-options')
            .find('div.navigator-group.open')
            .hide()
            .end()
            .find('ul.tabs-list')
             .addClass('disable');
        $('div.slider')
            .slider('disable');

        if (!$('#searchbar-outer').length) {
            validateSearch(true, ($input && $input.value != "") ? 'Location not recognised' : 'Please enter a location');
        }
    }
}

function toggleSliders(state) {
    var disabledSliders = $('div.slider.ui-state-disabled').length,
        status = (state === false) ? 'disable' : 'enable';
    if ((disabledSliders > 0 && state === true) || (disabledSliders === 0 && state === false)) {
        $('div.slider')
            .slider(status);
    }
}

// Validate the search and apply validation tooltip or not as required. 
function validateSearch(force, message) {

    var $location = document.getElementById('nav-postcode'),
        invalidAlertID = 'validation-alert',
        $invalidAlert = document.getElementById(invalidAlertID),
        message = (message) ? message : 'Please enter a location';
    result = false;

    if ($location.value == "" || force == true) {
        if (!$invalidAlert) {
            $invalidAlert = document.createElement('div');
            if (!$("#searchbar-outer").length) {
                $($location.parentNode.appendChild($invalidAlert))
                .attr('id', invalidAlertID)
                .attr('class', 'validation-tooltip')
                .html(message + ' <img src="http://cdn2.motors.co.uk/v2live/images/validation-alert-arrow-left-e16702.' + (($(document.body).hasClass('ie6')) ? 'gif' : 'png') + '"/>')
                .bind('click', function () {
                    $(this).remove();
                });
            }
        }
        $($location).addClass('empty').focus();

    } else {

        $($location).removeClass('empty');
        if ($invalidAlert) {
            $location.parentNode.removeChild($invalidAlert);
        }
        result = true;

    }
    return result;
}

/*
*  Input Placeholder Text
*  Syntax:
*  $('.carfinder').find('label').each(function () {
*      var $inp = $('#' + $(this).attr('for'));
*      inFieldHandler($(this), $inp);
*  });
*/
var inFieldHandler = function ($lbl, $inp) {

    var lblText = $lbl.text(); //get the labels text
    var gray = {
        'color': '#777' //set gray for when field not filled
    };
    $inp.css('color', '#777').val(lblText); //place label text into input
    $lbl.hide(); //hide label
    if ($inp.is(':text')) { //input must be text
        $inp.focus(function () { //on focus if value = labels text empty value
            if ($inp.val() == lblText) $inp.css('color', '#000').val('');
        }).blur(function () { //on blur place label text back in if empty
            if (!$inp.val() || $inp.val().replace(/^\s+|\s+$/g, '') == '') $inp.css(gray).val(lblText);
        });
    } else if ($inp.is('select')) {  //or input must be select
        $inp.children('option[value=""]').remove(); //remove any previous empty options
        $inp.prepend('<option selected="selected">' + lblText + '...</option>'); //add in label text as valueless option
    }
};
/* End Input Placeholder Text code */


/*
*  Insert Google Map
*  Used: Dealer Search Results, Dealer Stocklist, ThisIs Used Car tabs
*  Syntax: googleMap(<start location>, <end location>, <id of map element as string, not a selector or obj>)
*/
function googleMap(start, end, elId) {

    var geocoder, map, directionDisplay, directionsService, myOptions, request, marker, link;

    if (elId == '' || typeof elId == 'undefined') { elId = 'map-canvas' }

    myOptions = {
        zoom: 12,
        mapTypeControl: true,
        mapTypeControlOptions: { style: google.maps.MapTypeControlStyle.DROPDOWN_MENU },
        navigationControl: true,
        navigationControlOptions: { style: google.maps.NavigationControlStyle.SMALL },
        mapTypeId: google.maps.MapTypeId.ROADMAP
    }

    map = new google.maps.Map(document.getElementById(elId), myOptions);

    $.extend(googleMap, {
        staticLink: function () {
            link = 'http://maps.google.co.uk/maps?f=q&source=s_q&hl=en&q=' + end.replace(new RegExp(', ', 'g'), ',+');
            $(document.getElementById(elId))
                .parent()
                .append('<a rel="external" class="viewGoogleMap" target="_blank" href="' + link + '" style="font-size:10px;">View in Google Maps</a>');
        },
        directions: function () {
            //directions
            directionsService = new google.maps.DirectionsService();
            directionsDisplay = new google.maps.DirectionsRenderer();
            directionsDisplay.setMap(map);
            request = {
                origin: start,
                destination: end,
                travelMode: google.maps.DirectionsTravelMode.DRIVING
            };
            if (directionsService) {
                directionsService.route(request, function (result, status) {
                    if (status == google.maps.DirectionsStatus.OK) {
                        directionsDisplay.setDirections(result);
                    } else {
                        googleMap.geocoding();
                    }
                });
            } else {
                googleMap.geocoding();
            }
        },
        geocoding: function () {
            //geocoding
            geocoder = new google.maps.Geocoder();
            if (geocoder) {
                geocoder.geocode({ 'address': end, 'region': 'GB' }, function (results, status) {
                    if (status == google.maps.GeocoderStatus.OK) {
                        map.setCenter(results[0].geometry.location);
                        var contentString = '<div id="content">' +
                                                '<p>' + end.replace(/, /g, '<br>') + '</p>' +
                                            '</div>';

                        var infowindow = new google.maps.InfoWindow({
                            content: contentString
                        });
                        marker = new google.maps.Marker({
                            map: map,
                            position: results[0].geometry.location
                        });
                        google.maps.event.addListener(marker, 'click', function () {
                            infowindow.open(map, marker);
                        });
                    } else {
                        if (end.length > 1) {
                            end = end.substr(end.indexOf(',') + 1);
                            googleMap.geocoding();
                        } else {
                            document.getElementById(elId).innerHTML = '<h1>Sorry, we were unable to find this address. You can contact the seller by telephone or email via the search results.</h1>';
                        }
                    }
                });
            }
        }
    });

    // directions disabled because the postcodes are a bit flakey for locating anyhting in google maps api. weirdly the regular maps thing works fine.
    //if (start != '' && end != '') {
    //    googleMap.directions();
    //} else if (start == '' && end != '') {
    //    googleMap.geocoding();

    if (end != '') {
        googleMap.geocoding();
    } else {
        document.getElementById(elId).innerHTML = '<h1>No address specified.</h1>';
    }

    googleMap.staticLink(); // insert link to google maps

    if ((typeof _gaq != 'undefined')) {
        _gaq.push(['_trackEvent', 'ViewMap', (arguments.length > 3) ? arguments[3] : 'Dealer', end]);
        _gaq.push(['_trackPageview']);
    }
}
/* End Insert Google Map code*/


/*
*  Lightweight Content Rotators
*  Used: ThisIs Used Cars, ThisIs Homepage
*  Syntax: rotatorInit(<selector or object>)
*/
function slideLeft(nextPos, target, obj, objId, currentEl) {
    nextPos = rotatorContent[objId][nextPos + 1] ? nextPos + 1 : 0;
    target = target === undefined || isNaN(target) ? rotatorContent[objId][nextPos].html : rotatorContent[objId][target].html;
    $("div.rotator-panel-container", obj)
		.append('<div class="rotator-panel" id="' + objId + "-" + nextPos + '">' + target + "</div>")
		.animate({ marginLeft: "-" + currentEl.width() }, 300, function () {
		    $(this)
				.css("margin-left", "0px")
				.find("div.rotator-panel:first")
				.remove();
		});
    return nextPos;
}
function slideRight(nextPos, target, obj, objId, currentEl) {
    nextPos = rotatorContent[objId][nextPos - 1] ? nextPos - 1 : rotatorContent[objId].length - 1;
    target = target === undefined || isNaN(target) ? rotatorContent[objId][nextPos].html : rotatorContent[objId][target].html;
    $("div.rotator-panel-container", obj)
		.css("margin-left", "-" + currentEl.width() + "px")
		.prepend('<div class="rotator-panel" id="' + objId + "-" + nextPos + '">' + target + "</div>")
		.animate({ marginLeft: 0 }, 300, function () {
		    $(this)
				.find("div.rotator-panel:last")
				.remove();
		});
    return nextPos;
}
function doRotate(obj, direction, target) {
    var currentPos, currentEl, objId, pageUrl, dealerId, auditUrl;
    obj = $(obj);
    objId = obj.attr("id");
    currentEl = $("div.rotator-panel:first", obj);
    if (isNaN(target)) { // can't just check if(target){..} apparently firefox treats 0 as null for reasons unknown
        currentPos = currentEl.attr("id");
        currentPos = parseInt(currentPos.substr(currentPos.lastIndexOf("-") + 1), 10);
    } else {
        currentPos = target + 1;
    }
    currentPos = (direction && direction.substr(0, 1).toLowerCase() == "r") ? slideRight(currentPos, target, obj, objId, currentEl) : slideLeft(currentPos, target, obj, objId, currentEl);
    obj.parent().find('div.usedCarThumbnails')
        .find('a.active').removeClass('active').end()
        .find('a.thumbnail:nth-child(' + (currentPos + 1) + ')').addClass('active');

    dealerId = $('div.rotator-panel:first').find('img:first').attr('src').split('/used-photos/')[1].substr(0, 5);

    if ((typeof _gaq != 'undefined')) {
        _gaq.push(['_trackEvent', 'ViewImage', 'Dealer', ]);
        _gaq.push(['_trackPageview', 'used-car-view/' + dealerId + '/image-' + (currentPos + 1)]);
    }

    auditUrl = '/audit/image/' + currentPos + '/' + objId.split('-')[1] + '/' + dealerId;

    $.post(auditUrl);
}
function rotatorInit(obj) {

    obj = $(obj);
    if (obj.length === 0) { return false; }

    var objId = obj.attr('id'),
        jsonObj = [],
        thumbs = obj.parent().find('div.usedCarThumbnails a.thumbnail');

    // build JSON object & bind thumbnail clicks
    if (thumbs.length == 0) { return false; }
    thumbs.each(function (i, el) {
        $t = $(this);
        if ($t.hasClass('video')) {
            var o = [];
            o.width = '400';
            o.height = '225';
            o.type = 'rtmp';
            o.streamer = 'rtmp://flv2.motors.co.uk/ondemand';
            o.file = $('img', el).attr('alt');
            o.id = 'used-videos';
            o.javascriptid = 'mediaplayer';
            o.image = 'http://cdn2.motors.co.uk/v2live/images/logo.png';
            o.enablejs = 'true';
            o.plugins = 'gapro-1&amp;gapro.accountid=UA-1084356-1&amp;gapro.trackstarts=true&amp;gapro.trackpercentage=true&amp;gapro.tracktime=true';
            jsonObj.push({ "html": '<embed width="' + o.width + '" height="' + o.height + '" flashvars="width=' + o.width + '&amp;height=' + o.height + '&amp;type=' + o.type + '&amp;streamer=' + o.streamer + '&amp;file=' + o.file + '&amp;id=' + o.id + '&amp;javascriptid=' + o.javascriptid + '&amp;image=' + o.image + '&amp;enablejs=' + o.enablejs + '&amp;plugins=' + o.plugins + '" wmode="transparent" fixie8bug="true" allowscriptaccess="always" allowfullscreen="false" quality="high" name="mediaplayer" id="mediaplayer" style="" src="http://cdn2.motors.co.uk/v2live/images/media/player.swf" type="application/x-shockwave-flash">' });
        } else {
            jsonObj.push({ "html": "<img src=" + $('img', el).attr('alt') + " />" });
        }
        $t.click(function () {
            doRotate($(this).parent().parent().find('.usedCarRotator'), "r", $(this).prevAll().length);
        });
    });
    rotatorContent[objId] = jsonObj;

    // populate rotator
    obj
		.html('<div class="rotator-panel-container"><div id="' + objId + '-0" class="rotator-panel">' + rotatorContent[objId][0].html + '</div></div>');

    // add and bind controls if there is more than 1 image
    if (thumbs.length > 1) {
        obj
		    .append('<a href="#" class="rotator-move left" title="Previous">&lt;</a>')
		    .append('<a href="#" class="rotator-move right" title="Next"> &gt;</a>')
		    .bind({
		        mouseenter: function () {
		            $(this).addClass("inside");
		        },
		        mouseleave: function () {
		            $(this).removeClass("inside");
		        }
		    });
        // bind controls
        $("a.rotator-move.right", obj).click(function (event) {
            event.preventDefault();
            doRotate($(this).parent(), "l");
        });
        $("a.rotator-move.left", obj).click(function (event) {
            event.preventDefault();
            doRotate($(this).parent(), "r");
        });
    } else {
        thumbs.remove();
    }
}

/*
* New Rotator (v2)
*
* USAGE: in the json object "rotatorContent" there should be an object with the same name as the ID of the rotator element. It should 
* contain an array of obvjects with a value named of "content" containing the rotator item markup (with escaped quotes). Any objects
* without the "content" value will be stripped out of the object when the rotator is initialised. You can also supply a "title" value
* to display text in the page menu rather than a number. Uses jQuery for the animation and some other bits and pieces, but tbh it could
* quickly be adapted to not use it if it's desperately important.
*
* Seperate persistent objects set up for each rotator within the main object, so you can have multiple rotators on the same page all 
* controlled from the same place. If there is only one item in the JSON no controls will be shown and the class no-controls will be 
* added to the target id. If no autoRotateInterval is specified then it won't autorotate.
*
* SYNTAX: newRotator.init( rotatorId[string], showPageControls[true|false], autoRotateInterval[integer] );
* EXAMPLE: newRotator.init('cotwRotator', false, 1000);
*/


var newRotator = (function () {

    var config = {},
        init;

    function updatePageMenu(c) {
        if ($('ul.page-menu', c.obj).length > 0) {
            $('#' + c.objId + '-page a.active').removeClass('active');
            $('#' + c.objId + '-page-' + c.currentPos).addClass('active');
        }
    }

    /*
    setInterval does not wait until the previous function has finished before executing. If somebody sets a very low interval
    on a very wide rotator this could cause problems (hello, multiple concurrent stacked animate events). Not really an issue at 
    the moment, but do something like this if it becomes a problem. Probably need to check for c.abort in the rotate functions 
    too, incase the timeout was initialised before the event was aborted. Not included this because it feels a bit bloaty and
    tbqfh since we're setting the rotator params ourselves so i'd hope they work.

    function recurse(task, c) {
    setTimeout(function () {
    task();
    if (c.autoRotate !== null)
    autoRotate(callback, c);
    }, c.interval);
    };

    c.autoRotate = recurse(function, c);
    */

    function rotateToTarget(c, target) {
        if (target < c.currentPos) {
            rotateContentLeft(c, target);
        } else if (target > c.currentPos) {
            rotateContentRight(c, target);
        } else {
            return false;
        }
    }

    function rotateContentLeft(c, target) {
        var json = rotatorContent[c.objId],
            nextPos = (c.currentPos <= 0) ? json.length - 1 : c.currentPos - 1,
            content = (target) ? json[target].content : json[nextPos].content,
            objParent = $("div.rotator-panel-container", c.obj);
        if (objParent.length === 0 || objParent.find('div.rotator-panel').length > 1) {
            return false;
        }
        nextPos = (target) ? target : nextPos;
        objParent[0].firstChild.className = "rotator-panel"; // remove class 'active' from inactive panel (used to hide the image with the css)
        objParent[0].innerHTML = '<div class="rotator-panel active" id="' + c.objId + "-" + nextPos + '">' + content + '</div>' + objParent[0].innerHTML;
        objParent
            .css({ marginLeft: "-" + c.objWidth + "px" })
		    .animate({ marginLeft: 0 }, c.objWidth, 'linear', function () {
		        $(this)
				    .find("div.rotator-panel:last")
				    .remove();
		    });
        c.currentPos = parseInt(nextPos, 10);
        updatePageMenu(c);
    }

    function rotateContentRight(c, target) {
        var json = rotatorContent[c.objId],
            nextPos = (json[c.currentPos + 1]) ? c.currentPos + 1 : 0,
            content = (target) ? json[target].content : json[nextPos].content,
            objParent = $("div.rotator-panel-container", c.obj);
        if (objParent.length === 0 || objParent.find('div.rotator-panel').length > 1) {
            return false;
        }
        nextPos = (target) ? target : nextPos;
        objParent[0].firstChild.className = "rotator-panel"; // remove class 'active' from inactive panel (used to hide the image with the css)
        objParent[0].innerHTML += '<div class="rotator-panel active" id="' + c.objId + "-" + nextPos + '">' + content + '</div>';
        objParent
            .animate({ marginLeft: "-" + c.objWidth }, c.objWidth, 'linear', function () {
                $(this)
                    .css({ marginLeft: "0px" })
				    .find("div.rotator-panel:first")
				    .remove();
            });
        c.currentPos = parseInt(nextPos, 10);
        updatePageMenu(c);
    }

    function bindRotatorControls(c) {
        $("a.rotator-move", c.obj).click(function (event) {
            event.preventDefault();
            var c = config[this.id.substring(0, this.id.lastIndexOf('-'))], doRotate;
            if (c.interval)
                clearTimeout(c.autoRotate);
            if (this.className.indexOf('right') > -1) {
                doRotate = function () { rotateContentRight(c) };
            } else {
                doRotate = function () { rotateContentLeft(c) };
            }
            doRotate();
            if (c.interval)
                c.autoRotate = setInterval(doRotate, c.interval);
        });
        $("ul.page-menu a", c.obj).click(function (event) {
            event.preventDefault();
            var tempId = this.id.split('-page-'),
                c = config[tempId[0]];
            //console.log(c.autoRotate);
            if (c.interval)
                clearTimeout(c.autoRotate);
            rotateToTarget(c, tempId[1]);
        });
    }

    function buildRotatorContent(c, json) {
        var objHtml = '<div class="rotator-panel-container"><div id="' + c.objId + '-0" class="rotator-panel active">' + json[0].content + '</div></div>',
            objUl = '',
            objClass = '',
            title;
        if (c.objCount > 1) {
            objHtml += '<a href="#" id="' + c.objId + '-left" class="rotator-move left" title="Previous">&lt;</a>';
            if (c.createPageList === true) {
                for (i = 0; i < c.objCount; i++) {
                    title = json[i].title;
                    if (title === undefined || title === '') {
                        title = i + 1;
                    }
                    objUl += '<li><a href="#" id="' + c.objId + '-page-' + i + '" class="' + ((i === 0) ? 'active' : '') + '">' + title + '</a></li>';
                }
                objHtml += '<ul id="' + c.objId + '-page" class="reset page-menu">' + objUl + '</ul>';
            }
            objHtml += '<a href="#" id="' + c.objId + '-right" class="rotator-move right" title="Next">&gt;</a>';
        } else {
            objClass += 'no-controls';
        }
        c.obj.innerHTML = objHtml;
        c.objWidth = document.getElementById(c.objId + '-0').offsetWidth;
        c.obj.className = objClass;
        if (json.length > 1)
            bindRotatorControls(c);
        if (c.interval)
            c.autoRotate = setInterval(function () { rotateContentRight(c) }, c.interval);
    }

    init = function (rotator, createPageList, interval) {
        var c, json, obj = document.getElementById(rotator), i = 0, intervalVal;
        if (obj) {
            config[rotator] = {};
            c = config[rotator];
            c.obj = obj;
            c.objId = rotator;
            json = rotatorContent[c.objId];
            //console.log(rotatorContent);
            if (json) {
                for (; i < json.length; i++) {
                    if (!json[i].content) { json.splice(i, 1) };
                }
                c.objCount = (json) ? json.length : 0;
                c.currentPos = 0;
                c.createPageList = createPageList;
                c.obj.innerHTML = '<p class="info">Loading...</p>';
                if (interval) {
                    intervalVal = parseInt(interval, 10);
                    c.interval = (intervalVal >= 1000) ? intervalVal : 1000;
                }
                buildRotatorContent(c, json);
            } else {
                c.obj.innerHTML = '<p class="info">No content available.<p>';
            }
        }
    };

    return {
        init: init
    };

} ());

/* End New Rotator code */




/*
*  AND banner ads
*  Used: it'd be easier to list the places there aren't adverts :(
*  Syntax : called onload. Applied to iframes
*  <iframe class="andBanner" id="<id>" name="<id>" src="/andbanners.html?target=<%= HttpUtility.UrlEncode(AndBannerTarget) %>" width="120" height="600" scrolling="no" frameborder="0">
*	    <p>Your browser does not support iframes.</p>
*  </iframe>
*
*  TODO: ideally the name and id shouldn't be the same. a unique identifier is hardly unique if there are two attribs with the same value!
*/
function refreshAds() {

    var args = arguments,
        currentTime = new Date(),
        count = 0,
        banners = {},
        sitename = '',
        thisis = false,
        jp = false,
        bodyClass = (document.body.className && (document.body.className !== null)) ? document.body.className.toString().toLowerCase() : undefined;

    //check for body class
    if (bodyClass) {
        //if thisis
        if (bodyClass.indexOf('thisis') > -1) {
            thisis = true;
            sitename = window.location.hostname.split('.')[1].toLowerCase();
        }

        //if jp
        if (bodyClass.indexOf('jp') > -1) {
            jp = true;
            var adSiteName = document.getElementById('adSiteName');
            sitename = (adSiteName) ? adSiteName.value : 'motors.jp/motors';
        }
    }

    function getElementsByClass(searchClass, node, tag) {
        var classElements = [],
            els, elsLen,
            pattern = new RegExp('(^|\\\\s)' + searchClass + '(\\\\s|$)');

        if (node === undefined || node === null) { node = document; }
        if (tag === undefined || tag === null) { tag = '*'; }

        els = node.getElementsByTagName(tag);
        elsLen = els.length;

        for (var i = 0, j = 0; i < elsLen; i++) {
            if (pattern.test(els[i].className)) {
                classElements[j] = els[i];
                j++;
            }
        }
        return classElements;
    }
    //banner ads
    banners = getElementsByClass('andBanner');

    //if thisis add ID and Name to each iframe
    if (thisis) banners = banners.concat(getElementsByClass('thisisad'));

    //JP ad banners to banner obj
    if (jp) banners = banners.concat(getElementsByClass('jpad'));

    function callAdvert(bnrId) {
        if (banners[bnrId] && banners[bnrId].id) {
            var id = banners[bnrId].id,
            elm = document.getElementById(id),
            bannerName = window[id],
            src = elm.getAttribute('src'),
            sz = elm.getAttribute('width') + 'x' + elm.getAttribute('height'),
            szArr = ['728x90', '468x60'],
            sn = '&sn=';

            //only for top leaderboard ad
            if (id == 'topBanner') sz = szArr[Math.floor(Math.random() * szArr.length)];

            //if ajax call with args
            if (args.length) src = args[0] + ';';

            //change site name if thisisad
            if (id.indexOf('thisisad') > -1) {
                sn += sitename;
                // removed to prevent duplicate tiles
                //src += escape('?tile=' + id.split('_')[1] + ';dcopt=ist;');
            }

            //change site name if jpad
            if (id.indexOf('jpad') > -1) {

                var tile = function (adsize) {
                    var tileType = 1;

                    if (adsize == '120x600' || adsize == '160x600') {
                        tileType = 2;
                    } else if (adsize == '300x250') {
                        tileType = 3;
                    }

                    return {
                        type: tileType
                    };
                } (sz);

                sn += sitename;
                src += escape('tile=' + tile.type + ';');
            }

            //bannerName.location = src + '&sz=' + sz + '&id=' + id + sn + '&t=' + currentTime.getTime();
            bannerName.location.replace(src + '&sz=' + sz + '&id=' + id + sn + '&t=' + currentTime.getTime());
        }
    }

    //recursive call stack
    (function advertLoop() {
        var t;
        callAdvert(count);
        count++;
        if (count < banners.length) {
            t = setTimeout(advertLoop, 100);
        } else {
            clearTimeout(t);
        }
    })();
}
/* End AND banners code */

/* MITULA DEALER FORM */

function checkRequiredField(textBox, defaultText, requiredCssClass) {
    var inxTextBox = $.inArray(textBox.id, arrRequiredFields);

    if ((textBox.value.length == 0) || (textBox.value == defaultText)) {
        textBox.value = defaultText;
        textBox.className = requiredCssClass;
        textBox.style.color = '#989898';

        if (inxTextBox == -1) {
            arrRequiredFields.push(textBox.id);
        }
    }
    else {
        textBox.className = '';

        if (inxTextBox > -1) {
            arrRequiredFields.splice(inxTextBox, inxTextBox + 1);
        }
    }
}

function checkDefaultText(textBox, defaultText) {
    if (textBox.value.length == 0) {
        textBox.value = defaultText;
        textBox.style.color = '#989898';
    }
}

function hideDefaultText(textBox, defaultText) {
    if (textBox.value == defaultText) {
        textBox.value = '';
    }

    textBox.style.color = '#000000';
}

function changeClass(textBox, defaultText, cssClass) {
    if ((textBox.value.length == 0) || (textBox.value == defaultText)) {
        textBox.className = cssClass;
    }
    else {
        textBox.className = '';
    }
}

var isEmailCorrect = true;

function checkEmail(textBox, defaultText) {
    var errorSpan = document.getElementById('spEmailError');

    if ((textBox.value == defaultText) || (textBox.value.match(/^[A-Za-z0-9._%-]+@[A-Za-z0-9.-]+(\.[A-Za-z]{2,4})+$/))) {
        isEmailCorrect = true;
        errorSpan.style.display = 'none';
    }
    else {
        isEmailCorrect = false;
        errorSpan.style.display = 'inline';
    }
}


function checkRequiredFields() {
    return ((arrRequiredFields.length == 0) && (isEmailCorrect));
}

//this function checks whether it's drive24 or motors and returns a url
function checkDomain() {
    var localUrl = document.domain,
    strBuildDomain = "";

    if (localUrl.indexOf("drive24.co.uk") != -1) {
        strBuildDomain += "drive24.co.uk";
    }
    else {
        strBuildDomain += "motors.co.uk";
    }
    return strBuildDomain;
}




/*
*  social media stuff
*/

var social = function () {
    
    var addThisShare = function (targ) {
        var data = targ.name.split('|'),
            service,
            carid,
            title,
            addThisUrl = 'http://api.addthis.com/oexchange/0.8/forward/';
        if (data.length == 3) {
            service = data[0];
            carid = data[1];
            title = data[2];
            //addthis_sendto(service, url, title); <-- depractated from addThis because apparently it doesn't work properly
            window.open(addThisUrl + service + '/offer?url=' + escape("http://" + window.location.host + "/car-") + carid + '&title=' + title + '&description=' + title);
            //GA
            if ((typeof _gaq != 'undefined')) {
                _gaq.push(['_trackEvent', 'socialShare', service, carid]);
            }
            // AuditDB
            //// thong (no backend support)
        }
    };

    function smsSend(to, from) {
        var cookie = getCookie('motorsSocial_smsCount'),
            cookieInt = parseInt(cookie, 10),
            cookieVal = 0,
            cookieLimit = 50,
            popup = document.getElementById('smsPopup'),
            user = document.getElementById('userIP'),
            userIP,
            closeHtml = '<a href="javascript:void(0)" class="button" onclick="$(this.parentNode).fadeOut(\'fast\');">Close</a>',
            pointerHtml = '<img class="pointer" src="http://cdn2.motors.co.uk/v2live/images/sms/arrow-down.gif" />',
            dataArr = popup.nextSibling.name.split('|');
        if (cookie === null) {
            // there is no cookie
            cookieVal = 1;
        } else if (cookieInt >= cookieLimit) {
            // the user has sent too many SMS today
            popup.innerHTML = '<H4>Sorry, you have reached your SMS limit for today.</h4>' + closeHtml + pointerHtml;
            popup.className = 'messageResponse';
            return false;
        } else {
            // increment the cookie
            cookieVal = cookieInt + 1;
        }

        userIP = user.value;
        if (userIP == undefined || userIP == "") return false;

        popup.innerHTML = '<H4>Sending</h4>' + pointerHtml;
        popup.className = 'messageAjax';

        $.ajax({
            type: "GET",
            url: '/Ajax/sendSms.ashx?From=' + escape(from) + '&To=' + to + '&vehicleId=' + dataArr[0] + '&vehicleStandout=' + dataArr[1] + '&userIP=' + userIP + '&SearchGuid=' + $('#SearchGuid').val(),
            contentType: "text/html; charset=utf-8",
            success: function (response) {
                popup.className = 'messageResponse';
                if (response.length < 2000) {
                    popup.innerHTML = '<H4>' + response + '</h4>' + closeHtml + pointerHtml;
                    setCookie('motorsSocial_smsCount', cookieVal, '1');
                } else {
                    popup.innerHTML = '<H4>An error occured. Please try again.</h4>' + closeHtml + pointerHtml;
                }
                setCookie('motorsSocial_smsFrom', from, '100');
            },
            error: function () {
                popup.className = 'messageResponse';
                popup.innerHTML = '<H4>An error occured. Please try again.</h4>' + closeHtml + pointerHtml;
                setCookie('motorsSocial_smsFrom', from, '100');
            }
        });
    }

    function smsValidate() {
        var toField = document.getElementById('smsTo'),
            fromField = document.getElementById('smsFrom');
        if (toField && toField.className.indexOf('invalid') > -1 || isNaN(toField.value)) {
            toField.focus();
            toField.className = 'fail';
            return false;
        } else {
            toField.className = '';
        }
        if (fromField && fromField.className.indexOf('invalid') > -1) {
            fromField.focus();
            fromField.className = 'fail';
            return false;
        } else {
            fromField.className = '';
        }
        smsSend(toField.value, fromField.value);
    }

    var smsToAFriend = function (targ) {
        
        var smsPopup = document.getElementById('smsPopup'),
            carUrl = 'http://www.' + checkDomain() + '/car-' + targ.name.split('|')[0],
            fromCookie = getCookie('motorsSocial_smsFrom'),
            popupHtml;
        // if there is no smsPopup make one
        if (smsPopup === null) {
            smsPopup = document.createElement('div');
            smsPopup.setAttribute('id', 'smsPopup');
            // bind events on first load
            $(smsPopup)
                .find('a.submit').live('click', function () {
                    smsValidate();
                })
                .end()
                .find('a.cancel').live('click', function () {
                    smsPopup.style.display = 'none';
                    return false;
                })
                .end()
                .find('input')
                    .live('blur', function (e) {
                        var el = e.target;
                        el.value = trim(el.value);
                        if (el.id == 'smsTo')
                            el.value = el.value.replace(/[^0-9]/g, ''); // cheap preliminary validation for phone numbers
                        if (el.value == '') {
                            el.value = el.title;
                            el.className = 'invalid';
                        }
                    })
                    .live('focus', function (e) {
                        var el = e.target;
                        if (el.value == el.title) {
                            el.value = '';
                            el.className = '';
                        }
                    });
        } else {
            // if there is a popup on the current item hide it
            if (targ.previousSibling === smsPopup && smsPopup.style.display == 'block') {
                smsPopup.style.display = 'none';
                return false;
            }
        }
        popupHtml = '<h4>Text to a friend (SMS) for FREE</h4>';
        popupHtml += '<label for="smsTo">To:</label><input id="smsTo" class="invalid" type="text" title="Recipient\'s mobile phone number" value="Recipient\'s mobile phone number" maxlength="13" /><br/>';
        popupHtml += '<label for="smsFrom">From:</label><input id="smsFrom" type="text" title="Your Name" class="' + ((fromCookie === null) ? 'invalid" value="Your Name' : '" value="' + fromCookie) + '" maxlength="11" />'
        popupHtml += '<p class="smstext">I found this car on ' + checkDomain() + '. Thought you might be interested? <a href="' + carUrl + '">' + carUrl + '</a></p>';
        popupHtml += '<p class="misc"><strong>To/From fields required.</strong>Motors.co.uk will not use your data other than for this service.</p>';
        popupHtml += '<a href="javascript:void(0)" class="button submit" title="Send SMS now">Send</a>';
        popupHtml += '<a href="javascript:void(0)" class="button cancel" title="Close without sending">X</a>';
        popupHtml += '<img class="pointer" src="http://cdn2.motors.co.uk/v2live/images/sms/arrow-down.gif" />';
        targ.parentNode.insertBefore(smsPopup, targ);
        smsPopup.innerHTML = popupHtml;
        smsPopup.className = '';
        smsPopup.style.right = '6px';
        smsPopup.style.bottom = '32px';
        smsPopup.style.display = 'block';
    };

    return {
        share: addThisShare,
        sms: smsToAFriend
    };

} ();

//this is for SEO so it is ignored by robots and other things, sorry for this but couldn't think of another way!
function SeoHistoryCheck() {
    //get elements for the history panel
    var container = document.getElementById('historyCheckHolder');
    var elem_history = document.getElementById('HideSEO_historyCheck');
    var elem_historyLanding = document.getElementById('HideSEO_historyCheck_Landing');

    //TwoColumnLeft.master page history panel- there are two different styles not sure why?
    if (elem_history != null) {
        elem_history.innerHTML = '<h3 class="historyCheck"><span><img height="45" width="49" alt="History Check Icon" src="http://cdn2.motors.co.uk/v2live/images/bg_historycheckheader.gif" />History Check</span></h3><p>When you see this symbol you can be sure motors.co.uk has checked if a vehicle has been:</p><ul class="historyChecklist"><li>Stolen</li><li>Scrapped</li><li>Imported / Exported</li><li>Written-off</li></ul>';
        if (container != null) {
            container.style.visibility = 'visible';
        }
    }
    //SEO landing page history panel- there are two different styles not sure why?
    else if (elem_historyLanding != null) {
        elem_historyLanding.innerHTML = '<h3 class="clearfix"><span>History Check</span> <span class="icon"></span></h3><p>When you see this symbol you can be sure motors.co.uk has checked if a vehicle has been:</p><ul class="attention"><li>Stolen</li><li>Scrapped</li><li>Imported / Exported</li><li>Written-off</li></ul>';
        if (container != null) {
            container.style.visibility = 'visible';
        }
    }
}

//Microsoft decided to set one of the ads z-index to 9999999 so this loos through the divs within the ads and resets to 500.
function setAdvertZindex() {
    $('#AdTag_MotorsSkyScraper div, #AdTag_MotorsSkyScraper_TwoCol div, #AdTag_MotorsSkyScraper_SEO div').each(function () {
        $(this).css('z-index', '500');
    });
}

/*!
*  vehicledetails.js
*/

/*
* TODO: This file still needs refactoring. this entire section can be removed if we start using the static vehicle details pages.
*/

// jf_closewindow ought to only be called for the standalone details window, not the popup
// Probably also wants renaming and moving inside an object.

function jf_closewindow() {
    motors.curtain.raise();
    var veh = $('#vehicleDetails');
    if (veh.length > 0) {
        veh.find('.ajax').hide();
    }
    else {
        window.close();
    }
    //also will need to broadcast an event to any media player to stop playing any embedded SWF objects
}

var oldPhotoSmall;
function swapPhotos(oldPhotoLarge, CarID, newPhotoLarge, newPhotoSmall, ImageID) {
    var video = document.getElementById('video');
    if (video) {
        video.style.display = 'none';
    }
    if (!oldPhotoSmall) {
        oldPhotoSmall = 'photo_small_' + CarID;
    }
    oldPhotoLarge.style.display = 'block';
    if (document.getElementById('lrg_img'))
        document.getElementById('lrg_img').style.display = 'none';
    oldPhotoSmall.className = '';
    newPhotoSmall.className = 'selected';
    oldPhotoLarge.src = newPhotoLarge;
    oldPhotoSmall = newPhotoSmall;
    oldPhotoLarge.alt = newPhotoLarge;
    if ((typeof _gaq != 'undefined')) {
        _gaq.push(['_trackEvent', 'ViewImage', 'UsedCar', ]);
        _gaq.push(['_trackPageview', 'used-car-view/' + CarID + '/image']);
    }

    //    var imgUrlArr = newPhotoSmall.src.split('/'),
    //        imageId = imgUrlArr[7],
    var hidden = document.getElementById('tmpDealerID');
    if ((hidden) && (hidden.value != "")) {
        var dealerId = hidden.value;
    }
    else {
        var dealerId = 0;
    }

    var auditUrl = '/audit/image/' + ImageID + '/' + CarID + '/' + dealerId;
    
    $.post(auditUrl);
}
function togBoxesDisplay(boxID, buttonID) {
    document.getElementById('fullSpecsBox').style.display = 'none';
    document.getElementById('fullSpecsButton').className = '';
    document.getElementById('reviewsBox').style.display = 'none';
    document.getElementById('reviewsButton').className = '';
    document.getElementById('addedExtrasBox').style.display = 'none';
    document.getElementById('addedExtrasButton').className = '';
    document.getElementById('dealerInfoBox').style.display = 'none';
    document.getElementById('dealerInfoButton').className = '';
    document.getElementById(boxID).style.display = 'block';
    document.getElementById(buttonID).className = 'selected';
}
function swapVideo(img) {
    document.getElementById('video').style.display = 'block';
    img.style.display = 'none';
}
function trim(str) {
    str = this != window ? this : str;
    return str.replace(/^\s+|\s+$/g, "");
}
function showBMWForm(site) { // Used for bmw email
    window.open(site, "BMW", "status = 1, resizable = 0, location = 0, toolbar = 0, menubar = 0");
}
function showExtEmailForm(site, p_title, p_width, p_height) { // Used for generic email popup
    window.open(site, p_title, "status = 1, resizable = 0, location = 0, toolbar = 0, menubar = 0, width=" + p_width + ", height=" + p_height);
}
function toggleDiv(divid) { // Used inside benefits page
    $('#' + divid).toggle();
}
function toggleBenefits(div) {
    $(div).toggleClass('open');
}
function showToolTip() {

}

//this function gets the ID of the element clicked and gets the inner text(which is indented and not visable) and the title, the title is used as the heading and innertext as the message.
function populateMessageBox(id) {
    var elem = document.getElementById(id);
    if (elem) {
        //get message div
        var msgHtml = document.getElementById("motorsMsgBox");
        if (msgHtml) {
            //get heading element
            var heading = msgHtml.getElementsByTagName("h3")[0];
            if (heading) {       
                //add title of clicked element to heading         
                heading.innerHTML = elem.title;
            }
            var message = msgHtml.getElementsByTagName("p")[0];
            if (message) {
                //add inner HTML of clicked element to message body         
                message.innerHTML = elem.innerHTML;
            }
        }        
    }
}

function emailPrivateSeller() {
    //get the required form elements
    var elemName = document.getElementById("emailPSFord_fullName"),
    elemEmail = document.getElementById("emailPSFord_email"),
    isValid = true;

    //remove all messages
    $('#emailPSForm .error_text').remove();

    if ((elemName != null) && (elemEmail != null)) {
        //check if name has value
        if (elemName.value == "") {
            isValid = false;
            $('<p class="error_text">Please enter a full name.</p>').insertAfter($('#emailPSFord_fullName'));
        }
        //check if email is valid
        if (!isValidEmailAddress(elemEmail.value)) {
            isValid = false;
            $('<p class="error_text">Please enter a valid email address.</p>').insertAfter($('#emailPSFord_email'));
        }
        if (isValid) {
            //if passed validation then get the Ajax PS URL to send, will have car id on the end
            var elemUrl = document.getElementById("ajaxURLPS");
            if (elemUrl != null) {
                //send to private seller               
                $.ajax({
                    type: 'POST',
                    url: elemUrl.value,
                    data: $('#frmPSSend').serialize(),
                    context: document.body,
                    success: function () {
                        //display message to screen saying details sent successfully
                        var elemContainer = document.getElementById("emailPSForm");
                        if (elemContainer != null) {
                            elemContainer.innerHTML = "<h2>Thank you, your details have been sent.</h2>";
                        }
                    },
                    error: function () {
                        //add error message if problem
                        $('<p class="error_text">Sorry an error occurred while we tried to send your details, please try again or <a href="/cars/contact-us" target="_blank">contact us</a> if the error persists.</p>').insertAfter("#frmPSSend h2");
                    }
                });
            }
        } 
    }    
}
/*
if (motors.queryString === undefined) {
motors.queryString = (function (window) {
var queryArr = window.location.search.substr(1).split('&'),
queryObj = {},
temp;
for (var i in queryArr) {
if (queryArr.hasOwnProperty(i)) {
temp = queryArr[i].split('=');
queryObj[temp[0]] = temp[1];
}
}
return queryObj;
})(this);
}
*/

/*
*  body onload event
*/

$(document).ready(function () {

    //carfinder
    if ($('.carfinder').length) {
        $('.carfinder').find('label').each(function () {
            var $inp = $('#' + $(this).attr('for'));
            inFieldHandler($(this), $inp);
        });
    }
    //clean up JP affiliate logos for IE<8
    if ($('#jpFooterLogos').length && $('html').hasClass('ltie8')) {
        //for each affilTab class
        $('.affilTab').each(function () {
            //get the image inside
            var $img = $(this).find('img');
            //center by changing the top margin all containers are 90px high
            $img.css('margin-top', Math.round((90 - parseInt($img.height())) / 2));
        });
    }

    //social icons for search results
    $('div.controlContainer').find('a').live('click', function (e) {
        var targ = e.target;
        if (targ.className.indexOf('social') > -1) {
            e.preventDefault();
            social.share(targ);
        } else if (targ.className.indexOf('sms') > -1) {
            e.preventDefault();
            social.sms(targ);
        }
    });

    //call function onload
    SeoHistoryCheck();
    setAdvertZindex();
    $('div.detailsContainer h4 a').live('click', function (e) {
        setAdvertZindex();
    });

    $("#headStrip .history-checked a").live("mouseover", function () {
        $(this).siblings("div.toolTips").show();
    });

    $("#headStrip .history-checked a").live("mouseout", function () {
        $(this).siblings("div.toolTips").hide();
    });

    //search dealers by name
    $('a#dealer-name_search').click(function () {
        if (!$("#dealer-name_search").hasClass("button_disabled")) {
            dealerNameSearch();
        }
    });

    //if input is not empty then change button styles
    $('input#dealer-name').keyup(function (event) {
        if ($(this).val() != "") {
            $('a#dealer-name_search, a#reset_dealer_search').removeClass('button_disabled');
        }
        else {
            $('a#dealer-name_search, a#reset_dealer_search').addClass('button_disabled');
        }
    });

    //Ajax function not being called correctly so had to use this hack to get MPU in car results, this will need to be moved when motors.ajax is udpated
    $('#searchResultsHTML div.detailsContainer h4 a').click(function () {
        setTimeout('loadMPU()', 2000);
    });

    //SPP Test drives
    $('#searchTestDrives').click(function () {
        var form = $(this).parents('form:first');
        if (form != null) {
            var elemText = document.getElementById("search_text");
            if (elemText != null) {
                if (elemText.value == "") {
                    alert("Please enter a value to search test drives");
                    elemText.focus();
                }
                else {
                    form.submit();
                }
            }
        }
    });

    /*New Private Seller form*/
    $('#emailPSDetails').live("click", function () {
        emailPrivateSeller();
    });

    //GA insurance click tracking
    $('#searchResultsHTML .insurance .insurance_click').live("click", function () {
        _gaq.push(['_trackEvent', 'Addtional Search Result Options', 'Insurance']);
    });

    //GA insurance click tracking, vehicle details
    $('#insuranceInfo #getInsuranceQuote').live("click", function () {
        _gaq.push(['_trackEvent', 'Vehicle Details', 'Insurance']);
    });

    //GA insurance click tracking, vehicle details
    $('.contentBoxButtons a').live("click", function () {
        if (this.className == "retrieveQuote") {
            _gaq.push(['_trackEvent', 'Insurance - Get A Quote', 'Insurance']);
        }
        else {
            _gaq.push(['_trackEvent', 'Insurance - Retrieve Quote', 'Insurance']);
        }
    });

    /* Google Plus One */
    (function () {
        var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
        po.src = 'https://apis.google.com/js/plusone.js';
        var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
    })();

    //new Events for Olli, track events for Dealer site click in results and Pop up
    $('#dealerInfo .dealerwebsite a, #searchResultsHTML .imgContainer a[title="View dealer site"]').live("click", function () {
        refreshMSAds();
        var carId = getParameterByName('vehicleId', this.href),
        dealerID = getParameterByName('dealerId', this.href);

        if (dealerID != "") {
            _gaq.push(['_trackEvent', 'VDW Click', 'Click', 'Dealer ID,' + dealerID]);
        }

        if (carId != "") {
            //For new Ecom
            var orderID = (Math.floor(Math.random() * carId)).toString();

            //New Ecom - Linked(Search motorsajax for New Ecom)
            _gaq.push(['_addItem',
                orderID, //Order ID (Random number)*
                carId, //SKU/Code (Vehicle ID)*
                'VDW Click', //Product name (Description)
                dealerID, //category (Make/Model)
                '0', //Unit price*
                '1' //Quantity*
            ]);
        }
    });

    //new Events for Olli, widget clicks, matches up with motosajax.sponsoredLinks, below does the same thing but for SEO 
    //due to time constraints this could be more dynamic but unfortunately it's not!.
    $('#latestCarsWidget a.m-title').live("click", function () {
        refreshMSAds();
        var carId = getParameterByName('vehicleId', this.href);
        if (carId != "") {
            _gaq.push(['_trackEvent', 'C2C Click', 'eWidget', 'Vehicle ID,' + carId]);

            //For new Ecom
            var orderID = (Math.floor(Math.random() * carId)).toString();

            //New Ecom - Linked(Search motorsajax for New Ecom)
            _gaq.push(['_addItem',
            orderID, //Order ID (Random number)*
            carId, //SKU/Code (Vehicle ID)*
            'C2C Click', //Product name (Description)
            'eWidget', //category (Make/Model)
            '0', //Unit price*
            '1' //Quantity*
        ]);
        }
    });

    //new Events for Olli, SEO widget clicks, matches up with motosajax.sponsoredLinks 
    $('#seoLatestCarsWidget a.m-title').live("click", function () {
        refreshMSAds();
        var carId = getParameterByName('vehicleId', this.href);
        if (carId != "") {
            _gaq.push(['_trackEvent', 'C2C Click', 'Widget', 'Vehicle ID,' + carId]);

            //For new Ecom
            var orderID = (Math.floor(Math.random() * carId)).toString();

            //New Ecom - Linked(Search motorsajax for New Ecom)
            _gaq.push(['_addItem',
            orderID, //Order ID (Random number)*
            carId, //SKU/Code (Vehicle ID)*
            'C2C Click', //Product name (Description)
            'Widget', //category (Make/Model)
            '0', //Unit price*
            '1' //Quantity*
        ]);
        }
    });

    //show pop up for my motors
    $('a#myAccount').live('click', function (event) {
        if (this.className == "") {
            event.preventDefault();
            showPopMiddle("motorsLogin", "ps_display_block");
        }
    });

    //if click on blackout then ensure it hides and closes all pop ups
    $('#darkenScreen, .close_pop').live('click', function () {
        showHideBlackout("hide");
        $('.ps_display_block').removeClass('ps_display_block').addClass('ps_display_none');
    });

    //submit the form for login
    $('#myAccountLogin').live('click', function () {
        //remove all messages
        $('#motorsLogin .error_text').remove();

        var elemEmail = document.getElementById('UserName'),
        elemPass = document.getElementById('Password'),
        isValid = true;

        if (elemEmail) {
            //check if email is valid
            if (!isValidEmailAddress(elemEmail.value)) {
                isValid = false;
                $('<p class="error_text">Please enter a valid email address.</p>').insertAfter($('#UserName'));
            }
        }
        if (elemPass) {
            if (elemPass.value == "") {
                isValid = false
                $('<p class="error_text">Please enter a password.</p>').insertAfter($('#Password'));
            }
        }
        if (isValid) {
            var form = $(this).parents('form:first');
            if (form != null) {
                form.submit();
            }
        }
    });

    //send Alerts via handler
    $('#sendAlert').live('click', function () {
        refreshMSAds();
        var elemPostcode = document.getElementById("postcode");

        //check if logged class exists(Ajax will return non logged in anyway)            
        if (this.className.indexOf('loggedin') != -1) {
            $.ajax({
                type: 'POST',
                url: '/Ajax/PostCarfinder.ashx',
                data: $('#frmAlerts').serialize(),
                context: document.body,
                success: function () {
                    //hide search bar results and show message
                    $('#alertsHTML').addClass('hide');
                    $('#alertsMessage').removeClass('hide');
                    if (elemPostcode != null) {
                        _gaq.push(['_trackEvent', 'Carfinder Alerts', 'Success', elemPostcode.value.toUpperCase()]);
                    }
                },
                error: function () {
                    $('#alertsMessage').html('Sorry an error occured, please try again.').removeClass('hide');
                    if (elemPostcode != null) {
                        _gaq.push(['_trackEvent', 'Carfinder Alerts', 'Error', elemPostcode.value.toUpperCase()]);
                    }
                }
            });
        }
        else {
            WriteAlertCookie();
            showPopMiddle("motorsLogin", "ps_display_block");
        }
    });

    //for Janrain login
    $('#socialLogin, #logoutLink').live('click', function () {
        //get return URL from the backend, hidden field because per environment
        var returnUrl = document.getElementById('returnURLSocial');
        if (returnUrl != null) {
            //set session cookie
            setCookie('returnURL', returnUrl.value, 0, 'motors.co.uk');
        }
        WriteLogoutCookie();
    });

    //Add message box
    //show pop up for my motors
    $('a.msgcall').live('click', function (event) {
        populateMessageBox(this.id);
        showPopMiddle("motorsMsgBox", "ps_display_block");
    });

});

