//  $(document).ready(function() {

    $('#specialReports').hide();
    $('.hiddenRow').hide();
    


    $('.showRowsBelow').click(function() {
        $(this).toggleClass('active');
        var currentRow = $(this).attr('rel');
        $("tr.hiddenRow[rel='"+currentRow+"']").toggle();
    });




    // nav bar last item remove chevron - this is only for IE6 which does not understand last-child css - sadly


  $('#breadcrumb li:last-child a').css('background-image', 'none');

    // event bubbling
  $('a[rel*="external"]').click(function() {
      window.open($(this).attr('href'));
      return false;
  });

  $('a[rel*="popup"]').click(function(e) {
      var win = window.open($(this).attr("href"), "_blank", "width=700,height=700,left=50,top=50,scrollbars=yes");
      win.focus();
      return false;
  });

  $('a[rel*="videoPopup"]').click(function(e) {
      var win = window.open($(this).attr("href"), "videoPopup", "width=700,height=600,left=50,top=50,scrollbars=yes");
      win.focus();
      return false;
  });

  $(document.body).bind("click", function(e) {

  var $target = $(e.target);
  
      if ($target.attr('href') == '#latestReviews') {
          $('#specialReports').hide();
          $('#latestReviews').show();

          $target.parentNode.addClass('active');

          return false;
      }

      if ($target.attr('href') == '#specialReports') {
          $('#latestReviews').hide();
          $('#specialReports').show();

          $target.parentNode.addClass('active');

          return false;
      }

      // Alters width of edition select on valuation page if to wide

      //        if ($target.attr('id') == 'modelId') {
      //            $('.valuation #editionId').css('width', 'auto');
      //            return false;
      //        }

      // reviews picture gallery



      if ($target.attr('class') == 'thumb') {
          var thelink = $target.parent();

          var newsource = $('#mainGalleryImage').attr('src');
          var thesource = $target.attr('src');
          thesource = thesource.slice(thesource.lastIndexOf('/'), thesource.length);
          newsource = newsource.slice(0, newsource.lastIndexOf('/'));
          newsource = newsource + thesource;

          $('#mainGalleryImage').attr('src', newsource);

          $('.pictureThumbnails li a').removeClass('active');
          thelink.addClass('active');

          $('#prevImgL span').css('display', 'block');
          $('#nextImgL span').css('display', 'block');
          var pictureThumbNumber = thelink.parent().attr('rel');
          if (pictureThumbNumber == 1) {
              $('#prevImgL span').css('display', 'none');
          }

          var pictureThumbNumberLast = $('.pictureThumbnails li:last').attr('rel');
          if (pictureThumbNumberLast == pictureThumbNumber) {
              $('#nextImgL span').css('display', 'none');
          }

          return false;
      }



      if ($target.attr('class') == 'prev' && $target.parent().attr('id') == 'prevImgL') {

          $('#nextImgL span').css('display', 'block');

          var newsource = $('#mainGalleryImage').attr('src');
          newsource = newsource.slice(0, newsource.lastIndexOf('/'));
          var thesource = $('.pictureThumbnails li a.active img').attr('src');
          thesource = thesource.slice(thesource.lastIndexOf('/'), thesource.length);
          var idLiPrev = $('.pictureThumbnails li a.active').parent().prev().attr('id');

          if (null != idLiPrev) {

              var quick = '#' + idLiPrev;

              var srcPrevTh = $(quick).children().children().attr('src');
              srcPrevTh = srcPrevTh.slice(srcPrevTh.lastIndexOf('/'), srcPrevTh.length);
              srcPrevTh = newsource + srcPrevTh;

              $('#mainGalleryImage').attr('src', srcPrevTh);
              $('.pictureThumbnails li a').removeClass('active');

              var quicka = quick + ' a';
              $(quicka).addClass('active');

              $('#prevImgL span').css('display', 'block');
              var pictureThumbNumber = $('.pictureThumbnails li a.active').parent().attr('rel');
              if (pictureThumbNumber == 1) {
                  $('#prevImgL span').css('display', 'none');
              }


              return false;
          }
      }

      if ($target.attr('class') == 'next' && $target.parent().attr('id') == 'nextImgL') {

          $('#prevImgL span').css('display', 'block');

          var newsource = $('#mainGalleryImage').attr('src');
          newsource = newsource.slice(0, newsource.lastIndexOf('/'));
          var thesource = $('.pictureThumbnails li a.active img').attr('src');
          thesource = thesource.slice(thesource.lastIndexOf('/'), thesource.length);

          var idLiNext = $('.pictureThumbnails li a.active').parent().next().attr('id');

          var pictureThumbNumberL = $('.pictureThumbnails li:last').attr('rel') - 1;
          var currentPicNum = $('.pictureThumbnails li a.active').parent().attr('rel');

          if (currentPicNum == pictureThumbNumberL) {
              $('#nextImgL span').css('display', 'none');
          }

          if (null != idLiNext) {

              var quick = '#' + idLiNext;

              var srcNextTh = $(quick).children().children().attr('src');
              srcNextTh = srcNextTh.slice(srcNextTh.lastIndexOf('/'), srcNextTh.length);
              srcNextTh = newsource + srcNextTh;

              $('#mainGalleryImage').attr('src', srcNextTh);
              $('.pictureThumbnails li a').removeClass('active');

              var quicka = quick + ' a';
              $(quicka).addClass('active');

              return false;

          }

      }

  });


    var pictureThumbNumber = $('.pictureThumbnails li a.active').parent().attr('rel');
    if (pictureThumbNumber > 1) {
        $('#prevImgL span').css('display', 'block');
    }

    var pictureThumbNumberLast = $('.pictureThumbnails li:last').attr('rel');
    if (pictureThumbNumberLast != pictureThumbNumber) {
        $('#nextImgL span').css('display', 'block');
    }



    // some scripting for the homepage

    if ($("#findReviewOrPriceBox").length != 0) {

        $("#findAPrice").hide();

        $("#findAReviewLink").click(function() {
            $("#findAPrice").hide();
            $("#findReviewOrPriceBox #frmQS").show();
            $(".homeFieldsetNav .active").removeClass('active');
            $(this.parentNode).parent().addClass('active');

            return false;
        });

        $("#findAPriceLink").click(function() {
            $("#findAPrice").show();
            $("#findReviewOrPriceBox #frmQS").hide();
            $(".homeFieldsetNav .active").removeClass('active');
            $(this.parentNode).parent().addClass('active');

            return false;
        });

    }

    if ($("#reviewReportBox").length != 0) {

        $("#reviewSpecial1").hide();

        $("#latestNavLink0").click(function() {
            $("#reviewSpecial1").hide();
            $("#reviewSpecial0").show();
            $(".latestNav .active").removeClass('active');
            $(this).addClass('active');

            return false;
        });

        $("#latestNavLink1").click(function() {
            $("#reviewSpecial0").hide();
            $("#reviewSpecial1").show();
            $(".latestNav .active").removeClass('active');
            $(this).addClass('active');

            return false;
        });
    }

    // check make and model have been selected

    $("#findPriceSubmit").click(function() {
        if ($('#priceMake :selected').val() == 'null') {
            alert('Please select a make and model');
            return false;
        }
        if ($('#priceBodyRange :selected').val() == 'null') {
            alert('Please select a model');
            return false;
        }
    });

    $("#frmQSsubmit").click(function() {
        if ($('#MA :selected').val() == '' || $('#MA :selected').val() == 'null') {
            alert('Please select a make and model');
            return false;
        }
        if ($('#RT :selected').val() == '' || $('#RT :selected').val() == 'null') {
            alert('Please select a model');
            return false;
        }
    });

    // print link

    if ($("#subNav")) {
        $("#subNav").append("<li class=\"printPage\"><a href=\"#\">Print this page</a></li>");

        $(".printPage > a").click(function() {
            window.print()
        }
        );
    };

    // reviews landing page car chooser script

    if ($("#carPropertyBrowser").length != 0) {

        $("#neworusedFieldset").hide();
        $("#pricingFieldset").hide();
        $("#bodystyleFieldset").hide();
        $("#greenFieldset").hide();
        $("#featuresFieldset").hide();

        $(".fieldsetNav a").click(function() {

            $("#pricingFieldset").hide();
            $("#neworusedFieldset").hide();
            $("#makeFieldset").hide();
            $("#bodystyleFieldset").hide();
            $("#greenFieldset").hide();
            $("#featuresFieldset").hide();

            $(".fieldsetNav .active").removeClass('active');

            var cutWhere = this.href.indexOf('#');
            var anker = this.href.substring((cutWhere + 1), this.href.length);

            document.getElementById(anker).style.display = "block";
            $(this.parentNode).addClass('active');

            return false;
        });

    }

    //script for review navigation
    if ($(".tabSection1").length != 0) {

        var urlHash = window.location.hash;
/*        $("a.tabRefreshUsed").click(function() {
            window.location.replace(($(this).attr('href')));
            window.location.reload();
            return false;
        });
        
 */       
        for (var i = 1; i <= 4; i++) {

            if ($(".tabSection" + i).hasClass("active")) {
                $("#section" + i).show();
            } else {
                $("#section" + i).hide();
            }
        }

        $(".tabSection1").click(function() {
            $("#section1").show();
            $(".tabSection1").addClass('active');
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');

            return false;
        });

        $(".tabSection2").click(function() {
            $("#section2").show();
            $(".tabSection2").addClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');

            return false;
        });

        $(".tabSection3").click(function() {
            $("#section3").show();
            $(".tabSection3").addClass('active');
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');

            return false;
        });

        $(".tabSection4").click(function() {
            $("#section4").show();
            $(".tabSection4").addClass('active');
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');

            return false;
        });
        
        

        if (urlHash == '#tabsection1') {
            $("#section1").show();
            $(".tabSection1").addClass('active');
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');
        }

        if (urlHash == '#tabsection2') {
            $("#section2").show();
            $(".tabSection2").addClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');
        }

        if (urlHash == '#tabsection3') {
            $("#section3").show();
            $(".tabSection3").addClass('active');
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
            $("#section4").hide();
            $(".tabSection4").removeClass('active');
        }

        if (urlHash == '#tabsection4') {
            $("#section4").show();
            $(".tabSection4").addClass('active');
            $("#section3").hide();
            $(".tabSection3").removeClass('active');            
            $("#section2").hide();
            $(".tabSection2").removeClass('active');
            $("#section1").hide();
            $(".tabSection1").removeClass('active');
        }

    }


    if ($(".tabRefresh").length != 0) {
/*
        $("a.reloadTab").click(function() {
            window.location.replace(($(this).attr('href')));
            window.location.reload();
            return false;
        });
*/


        $(".tabOwnership").click(function() {
            $("#ownership").show();
            $(".tabOwnership").addClass('active');
            $("#onTheRoad").hide();
            $(".tabOnTheRoad").removeClass('active');
            $("#inTheCabin").hide();
            $(".tabInTheCabin").removeClass('active');
            return false;
        });

        $(".tabOnTheRoad").click(function() {
            $("#ownership").hide();
            $(".tabOwnership").removeClass('active');
            $("#onTheRoad").show();
            $(".tabOnTheRoad").addClass('active');
            $("#inTheCabin").hide();
            $(".tabInTheCabin").removeClass('active');
            return false;
        });

        $(".tabInTheCabin").click(function() {
            $("#ownership").hide();
            $(".tabOwnership").removeClass('active');
            $("#onTheRoad").hide();
            $(".tabOnTheRoad").removeClass('active');
            $("#inTheCabin").show();
            $(".tabInTheCabin").addClass('active');
            return false;
        });

        
        if (urlHash == '') {
            urlHash = '#OnTheRoad';
        }
        
        if (urlHash == '#OnTheRoad') {
            $("#ownership").hide();
            $("#onTheRoad").show();
            $("#inTheCabin").hide();
            $(".tabOwnership").removeClass('active');
            $(".tabOnTheRoad").addClass('active');
            $(".tabInTheCabin").removeClass('active');
        }

        if (urlHash == '#Ownership') {
            $("#ownership").show();
            $("#onTheRoad").hide();
            $("#inTheCabin").hide();
            $(".tabOwnership").addClass('active');
            $(".tabOnTheRoad").removeClass('active');
            $(".tabInTheCabin").removeClass('active');
        }

        if (urlHash == '#InTheCabin') {
            $("#ownership").hide();
            $("#onTheRoad").hide();
            $("#inTheCabin").show();
            $(".tabOwnership").removeClass('active');
            $(".tabOnTheRoad").removeClass('active');
            $(".tabInTheCabin").addClass('active');
        }

    }
    
    



    //script for car verdict image map

    if ($(".description").length != 0) {

        $(".description>li").css("display", "none");
        $(".description1").css("display", "block");

        $(".indicator1").mouseover(function() {
            $(".description>li").css("display", "none");
            $(".description1").css("display", "block");
        });
        $(".indicator2").mouseover(function() {
            $(".description>li").css("display", "none");
            $(".description2").css("display", "block");
        });
        $(".indicator3").mouseover(function() {
            $(".description>li").css("display", "none");
            $(".description3").css("display", "block");
        });
        $(".indicator4").mouseover(function() {
            $(".description>li").css("display", "none");
            $(".description4").css("display", "block");
        });
        $(".indicator5").mouseover(function() {
            $(".description>li").css("display", "none");
            $(".description5").css("display", "block");
        });

    }


    //initializing tooltips


    //	$('.tooltip').tooltip({
    //		track: true,
    //		delay: 0,
    //		showURL: false,
    //		fixPNG: true,
    //		showBody: " - ",
    //		extraClass: "pretty fancy",
    //		top: -30,
    //		left: -20
    //	});

//    $('img[class="tooltip"]').bt({
//        titleSelector: "attr('title')",
//        fill: 'white',
//        cssStyles: { color: '#333', fontWeight: 'normal', width: 'auto' },
//        width: 400,
//        padding: 10,
//        cornerRadius: 5,
//        animate: true,
//        spikeLength: 10,
//        spikeGirth: 15,
//        positions: ['top'],
//        strokeStyle: "#ccc"
//    });


    var homepageLink = document.getElementById('homepage');
    if (homepageLink) {
        homepageLink.firstChild.onmouseover = function() {
            this.parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper3_over';
            this.parentNode.parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper2_over';
        }
        homepageLink.firstChild.onmouseout = function() {
            this.parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper3';
            this.parentNode.parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper2';
            if (homepageLink && (homepageLink.className == 'active')) {
                document.getElementById('homepage').parentNode.parentNode.parentNode.id = 'mainNavWrapper3_over';
                document.getElementById('homepage').parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper2_over';
            }
        }
    }

    if (homepageLink && (homepageLink.className == 'active')) {
        document.getElementById('homepage').parentNode.parentNode.parentNode.id = 'mainNavWrapper3_over';
        document.getElementById('homepage').parentNode.parentNode.parentNode.parentNode.id = 'mainNavWrapper2_over';
    }

    // media player - we don't know which qualities have been entered in the cms, so :first is our best option
    function activateWhatcarVideoMedia(mediaAnchorElement) {
        mediaAnchorElement = $(mediaAnchorElement);
        var targetContainerDiv = $("div#" + mediaAnchorElement.attr("id") + "Container");
        var targetContainerAnchor = $("a#" + mediaAnchorElement.attr("id") + "Container");

        // remove existing players
        var success = false;
        $("a.activeMedia").removeClass("activeMedia");
        $("div.media").hide();

        if (targetContainerDiv.attr("id") != null) {
            // player already initiated
            targetContainerDiv.show();
            success = true;
        }
        else
            if (targetContainerAnchor.attr("id") != null) {
            // init correct player
            var targetContainer = $("#" + mediaAnchorElement.attr("id") + "Container");
            if (targetContainer) {
                targetContainer.media({ autoplay: true, params: { controls: "ImageWindow,ControlPanel", center: "true", autosize: "false", transparentatStart: "true", ShowStatusBar: "true" }
                });
                success = true;
            }
        }
        if (success) {
            mediaAnchorElement.addClass("activeMedia");
        }
    }

    $("a.mediaTrigger").click(function(e) {
        e.preventDefault();
        activateWhatcarVideoMedia(this)
    });

    $(".mediaTrigger:first").each(function() {
        activateWhatcarVideoMedia(this);
    });

    $("a.mediaPopupWindowMedia").each(function() {
        $(this).media({ autoplay: true, params: { controls: "ImageWindow,ControlPanel", center: "true", autosize: "false", transparentatStart: "true", ShowStatusBar: "true"} });
    });


    // videos page

    if ($("#videoPlayerWrapper").length != 0) {

    }

    if ($(".radioStars")) {

        $(".radioStars>li label span").addClass('hidden');
        $(".radioStars>li input").addClass('hideInput');

        $(".radioStars>li input").click(function() {
            var starNumber = "radioStars clearfix readerRatingClicked" + this.value + " readerRating" + this.value;
            $(this.parentNode.parentNode).removeClass();
            $(this.parentNode.parentNode).addClass(starNumber);
        });

        $(".radioStars>li label").mouseover(function() {
            var parent = $(this).parent().get(0);
            var children = $(parent).find(":input").eq(0).each(
                function() {
                    if (!$(this.parentNode.parentNode).hasClass("readerRatingClicked" + this.value)) {
                        var starNumber = "radioStars clearfix readerRating" + this.value;
                        $(this.parentNode.parentNode).addClass(starNumber);
                    }
                }
            );
        });

        $(".radioStars>li label").mouseout(function() {
            var parent = $(this).parent().get(0);
            var children = $(parent).find(":input").eq(0).each(
                function() {
                    if (!$(this.parentNode.parentNode).hasClass("readerRatingClicked" + this.value)) {
                        $(this.parentNode.parentNode).removeClass("readerRating" + this.value);
                    }
                }
            );
        });
    }

    // Show/hide non-js box on home page
    $("#noJSMakeList").hide();
    $("#findAReview").show();
    //$("#findAPrice").show();


    // Price selector selects

    if ($("#pricingFieldset").length != 0) {
        $("#priceMin").change(function() {
            var pricefrom = Number($(this).attr("value"));
            $("#priceMax option").each(function() {
                var priceto = Number($(this).attr("value"));
                if (pricefrom >= priceto) {
                    $(this).hide();
                } else {
                    $(this).show();
                }
            });
            }
        )

            $("#priceFrom").change(function() {
                var pricefrom = Number($(this).attr("value"));
                $("#priceTo option").each(function() {
                    var priceto = Number($(this).attr("value"));
                    if (pricefrom >= priceto) {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                });
            }
        )

    }




//});


//    $.fn.clearForm = function() {


//        return this.each(function() {
//            var type = this.type, tag = this.tagName.toLowerCase();
//            if (tag == 'form') {
//                return $(':input', this).clearForm();
//            }
//            if (type == 'text' || type == 'password' || tag == 'textarea') {
//                this.value = '';
//            }
//            if (type == 'checkbox' || type == 'radio') {
//                this.checked = false;
//            }
//            if (tag == 'select') {
//                this.selectedIndex = 0;
//                alert("hello");
//            }
//        });

//    };



// GOOGLE ADVERTS
// turns nasty table-based text ads to prettier ones
function google_ad_request_done(google_ads) {
    var s = '';
    var i;
    if (google_ads.length == 0) {
        return;
    }
    if (google_ads[0].type == "image") {
        s += '<a href="' + google_ads[0].url +
              '" target="_top" title="go to ' + google_ads[0].visible_url +
              '"><img border="0" src="' + google_ads[0].image_url +
              '"width="' + google_ads[0].image_width +
              '"height="' + google_ads[0].image_height + '"></a>';

    } else if (google_ads[0].type == "flash") {
        s += '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
              ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0"' +
              ' WIDTH="' + google_ad.image_width +
              '" HEIGHT="' + google_ad.image_height + '">' +
              '<PARAM NAME="movie" VALUE="' + google_ad.image_url + '">' +
              '<PARAM NAME="quality" VALUE="high">' +
              '<PARAM NAME="AllowScriptAccess" VALUE="never">' +
              '<EMBED src="' + google_ad.image_url +
              '" WIDTH="' + google_ad.image_width +
              '" HEIGHT="' + google_ad.image_height +
              '" TYPE="application/x-shockwave-flash"' +
              ' AllowScriptAccess="never" ' +
              ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';

    } else if (google_ads[0].type == "text") {
        if (google_ads.length == 1) {
            s += '<div class="googleTextAdContainer">';
            s += '<a href="' + google_ads[0].url + '" ' +
                            'onmouseout="window.status=\'\'" ' +
                            'onmouseover="window.status=\'go to ' +
                            google_ads[0].visible_url + '\'">' +
                            '<span class="googleTextLine1">' + google_ads[0].line1 + '</span></a>' +
                            '<span class="googleTextLine2">' + google_ads[0].line2 + '</span>' +
                            '&nbsp;'+
                            '<span class="googleTextLine3">' + google_ads[0].line3 + '</span>' +
                            '<a href="' + google_ads[0].url + '" ' +
                            'onmouseout="window.status=\'\'" ' +
                            'onmouseover="window.status=\'go to ' +
                            google_ads[0].visible_url + '\'"><span class="googleTextUrl">' + google_ads[0].visible_url + '</span></a>' +
                            '</div>';
        } else if (google_ads.length > 1) {
            for (i = 0; i < google_ads.length; ++i) {
                s += '<div class="googleTextAdContainer"><a href="' + google_ads[i].url + '" ' +
                                  'onmouseout="window.status=\'\'" ' +
                                  'onmouseover="window.status=\'go to ' +
                                  google_ads[i].visible_url + '\'">' +
                                  '<span class="googleTextLine1">' + google_ads[i].line1 + '</span></a>' +
                                  '<span class="googleTextLine2">' + google_ads[i].line2 + '</span>' +
                                  '&nbsp;' +
                                  '<span class="googleTextLine3">' + google_ads[i].line3 + '</span>' +
                                  '<a href="' + google_ads[i].url + '" ' +
                                  'onmouseout="window.status=\'\'" ' +
                                  'onmouseover="window.status=\'go to ' +
                                  google_ads[i].visible_url + '\'"><span class="googleTextUrl">' + google_ads[i].visible_url + '</span></a>' +
                                  '</div>';
            }
        }
    }

    document.write(s);
    return;
}

