/* As with styles, we can will use the "universal" js file to define functions etc that are
to be used across the site. Anything for specific pages should go in the particulars folder */

document.observe("dom:loaded", function(event) {

    if($$('#revolving_testimonial li')[0]){
        rotate_testimonials()
    }
    if($('buyer_account_links')){
        is_logged_in()
    } // Perform any login related alterations if buyer_account_links present in DOM
    image_replacements();
    obfuscate_email('support');
    if($('quick_links')){
        quick_links(event)
    } // Pass window load event object.
    if($('bookmarker_link')){
        bookmarker()
    }

    if($('hear_testimonials')){
        testimonial_popup();
    }
});

function image_replacements() {
    $('main_title').replace('<img id="main_title" src="/images/header-title.gif" alt="RAC inspected ex-fleet cars direct from major brands at wholesale prices" />');
}

function obfuscate_email(user) {
    var dedashed_user = user.gsub('-', '.');
    var domain = 'carsite.co.uk';
    var address = dedashed_user + '@' + domain;
    $$('.'+ user +'_email').invoke('insert', '<a class="email" href="mailto:' + address + '" title="email ' + address + '">' + address + '</a>')
}

function obfuscate_name(person, special_chars_person) {
    var dashed_person = person.gsub(' ', '-').toLowerCase();
    if (special_chars_person){
        person = special_chars_person
    };
    $$('.obfuscated_' + dashed_person).invoke('insert', person)
}

function bookmarker(){
    $('bookmarker_link').observe('click', function(event) {
        var url = "http://www.carsite.co.uk/";
        var title = "Carsite: rac-inspected cars at wholesale prices";
        var ico = "/favicon.ico";
        if ((navigator.appName == "Microsoft Internet Explorer") && (parseInt(navigator.appVersion) >= 4)) {
            window.external.AddFavorite(url,title);
        } else if (navigator.appName == "Netscape") {
            window.sidebar.addPanel(title,url,ico);
        } else {
            alert("Press CTRL-D (Netscape) or CTRL-T (Opera) to bookmark");
        }
        event.stop();
    })
}

/************************************ Quick links panel in sidebar ************************************/
function quick_links(event) {
    // event here will be the window load event
    $$('#quick_links ul li ul').invoke('hide');
    $$('#quick_links ul')[0].insert('<a id="long_list_hide-show" href="#" title="show more/ less"></a>');
    $$('a.hide_models').invoke('hide');
    show_short_list(event);

    function show_short_list(event) {
        // triggered by either window load event or click event on long_list_hide-show
        $$('#quick_links ul li.long_list').invoke('hide');
        $('long_list_hide-show').update('show more makes');
        $('long_list_hide-show').stopObserving('click', show_short_list);
        $('long_list_hide-show').observe('click', show_long_list);
        event.stop();
    }
    function show_long_list(event) {
        $$('li.long_list').invoke('show');
        $('long_list_hide-show').update('show less makes');
        $('long_list_hide-show').stopObserving('click', show_long_list);
        $('long_list_hide-show').observe('click', show_short_list);
        event.stop();
    }
}
function show_models (make) {
    $$('ul.'+make)[0].show();
    $$('a.hide_models.'+make).invoke('show');
    $$('a.show_models.'+make).invoke('hide');
}
function hide_models (make) {
    $$('ul.'+make)[0].hide();
    $$('a.hide_models.'+make).invoke('hide');
    $$('a.show_models.'+make).invoke('show');
}

/************************************* Check if user is logged in ******************************************/
function is_logged_in() {
    new Ajax.Request('/buyer/IsBuyerLoggedIn.do',
    {
        method:'get',
        onSuccess: function(transport){
            var response = transport.responseText || "no response";
            if(response == 'true'){
                $$('a.login').invoke('replace', '<a id="logout" href="/buyer/Logout.do">logout</a>');
                $('logout').insert({
                    before: '<a href="/buyer/buyers-buddy.do">my folder</a> | '
                });
            }
        }
    // Do nothing if no successful request
    });
}

/************************************* simple date formatter ******************************************/
/** Produces date of format 1st January, 2000 from 3 numeric values **/
function format_date(day, month, year){
    var suffix = '';

    var st = [1, 21, 31]
    for(i=0;i<3;i++){
        if(st[i] == day){
            suffix = 'st';
        }
    }

    var nd = [2, 22]
    for(i=0;i<2;i++){
        if(nd[i] == day){
            suffix = 'nd';
        }
    }

    var rd = [3, 23]
    for(i=0;i<2;i++){
        if(rd[i] == day){
            suffix = 'rd';
        }
    }

    if(suffix == ''){
        suffix = 'th';
    }

    return day + suffix + ' ' + month + ', ' + year;
}

function rotate_testimonials() {
    // Ignore if test class set - simplifies dev debugging
    if ($('testimonials').hasClassName('test-class')) {
        return;
    }
    
    // Override default no-javascript styles
    $('testimonials').removeClassName('js_off');

    var testimonials = $$('#revolving_testimonial li');
    var delay_secs = 4;
    var delay_millisecs = 500;
    var fade_out_time = 0.5;
    var fade_in_time = 0.5;
    testimonials[0].writeAttribute('id', 'currently_displayed');

    // hide all but first:
    for (x=1;x<(testimonials.length);x++) {
        testimonials[x].hide()
    }

    // Set timer to iterate through testimonials, fading in and out
    new PeriodicalExecuter(function() {
        $('revolving_testimonial').fade({
            duration:fade_out_time
        });
        setTimeout('unhide()', delay_millisecs);
        setTimeout('$(\'revolving_testimonial\').appear({duration:'+fade_in_time+'})', delay_millisecs);
    }, (delay_secs * 2));
}

function unhide(){
    var current = $('currently_displayed');
    // Get the next testimonial, or go back to the 1st if we're already at the last
    var next = ($('currently_displayed').next() != null) ? $('currently_displayed').next() : $$('#revolving_testimonial li')[0];
    // Move the id to the next testimonial
    current.writeAttribute('id', '');
    current.hide();
    next.writeAttribute('id', 'currently_displayed');
    next.show();
}

function testimonial_popup(){
    $('hear_testimonials').observe('click', function(event) {
        window.open ("/flash/testimonial_podcast.html", "testimonial_podcast", "status=0,toolbar=0,location=0,menubar=0,resizable=0,scrollbars=0,width=460,height=19");
    })
}

// First rough attempt at method comparable to Rails' blank? Returns true if it
// is passed a 0, '0', '', or null value. Ideally would extend all objects to
// have this method.
function is_blank(e){
    if(e == '0' || e == '' || e == null || e == 0){
        return true;
    } else {
        return false;
    }
}

// Generic Carsite location Google map function
function map(lat, lng, zoom, map_type) {
  if (GBrowserIsCompatible()) {
    var map = new GMap2(document.getElementById("map"));
    map.setMapType(map_type);

    // Precise longtitude & latitude for Thurleigh handover centre
    map.setCenter(new GLatLng(lat, lng), zoom);
    point = new GLatLng(lat, lng);

    // Add our own icon for the pin
    var carsiteIcon = new GIcon(G_DEFAULT_ICON);
    carsiteIcon.image = "/images/particulars/contact/maps_icon.png";
    markerOptions = { icon:carsiteIcon };
    map.addOverlay(new GMarker(point, markerOptions));

    map.addControl(new GLargeMapControl());
    map.addControl(new GOverviewMapControl());

    // Add Geographic information from KML file
    geoXml = new GGeoXml("/carsite.kml");
    map.addOverlay(geoXml);
  }
}