function image_fader(old_image, new_image_path){
  if(new_image_path.length > 5) {
    if(!$.browser.msie){
      old_image.before(old_image.clone().attr("src",new_image_path).css({"z-index":3})).css({"z-index":4}).fadeOut("slow", function(){$(this).remove();});
    } else {
      old_image.attr('src', new_image_path);
    }
  }
}

$(document).bind("colours_ready",function() {
  $(".colour_pick .colour_swatch_container").eq(0).addClass("colour_swatch_selected");
  $(".colour_swatch").click(function(){
    $(".colour_pick .colour_swatch_container").removeClass("colour_swatch_selected");
    $("#config_form #cf_colour").val("name="+$(this).attr("data-colour")+"&transform="+$(this).attr("data-transform"));
    $(this).parent().addClass("colour_swatch_selected");
    $(".config_colour_val").html($(this).attr("data-colour"));
    var rgb_value = $(this).attr("data-rgb");
    $("#gallery_wrapper").animate({ backgroundColor:"#"+rgb_value},500);
    $(".model_image_area img").each(function(){
      $(this).attr("data-rgb",rgb_value);
    });
    
    var shot_angles = ["front","side","back"];
    for( var i in shot_angles){
      var main_image = $("img."+shot_angles[i]).eq(0);
      main_image.attr("alt",$(this).attr("data-colour")).attr("title",$(this).attr("data-colour"));
      image_fader(main_image, $(this).attr("data-image-"+shot_angles[i]));
    }
    init_360();
  });

  function init_360(){
    var f_slow = setInterval(function(){
      var flash_obj = jQuery("#fast360_flash object")[0];
      if(!flash_obj) flash_obj = jQuery("#fast360_flash")[0];
      if(flash_obj){
        if(typeof flash_obj.init_360 == "function"){
          clearInterval(f_slow);
          var images_360 = car360s[jQuery(".model_image_area img:first").attr("data-rgb")];
          if(images_360.length) flash_obj.init_360(images_360);
        }
      }
    }, 100);
  }
  
  swfobject.embedSWF("/flash/fast360.swf", "fast360", "100%", "100%", "8.0.0", "/flash/expressInstall.swf", {}, {swliveconnect:"true", allowscriptaccess:"always", wmode: 'transparent'}, {id:"fast360_flash"});

  jQuery("#button_360").click(function(e){
    var model_name = jQuery(this).attr("data-model-name");
    if(jQuery(this).hasClass("360_hidden")){
      jQuery(this).html(model_name+" <span>Normal</span> View");
      jQuery(".model_image_area").hide();
      jQuery("#fast360holder").show();
      init_360();
    }else{
      jQuery(this).html(model_name+" <span>360&deg;</span> View");
      jQuery(".model_image_area").show();
      jQuery("#fast360holder").hide();
    }
    jQuery(this).toggleClass("360_hidden");
    e.preventDefault();
  });
  
  if(jQuery("#interior_360")){
    var time_of_day = jQuery("#interior_360").attr("data-time");
    var interior_flash = "";
    if(time_of_day == "day") interior_flash = "11_Day_cube_v1_out.swf";
    else if(time_of_day == "night") interior_flash = "11_Night_cube_v1_out.swf";

    var flashvars = {};
    var params = {};
    params.quality = "high";
    params.bgcolor = "#ffffff";
    params.allowscriptaccess = "sameDomain";
    params.allowfullscreen = "true";
    params.base=".";
    var attributes = {};
    attributes.id = "pano";
    attributes.name = "pano";
    attributes.align = "middle";
    swfobject.embedSWF(
      "/flash/"+interior_flash, "fastinterior360", 
      "960", "720", 
      "9.0.0", "/flash/expressInstall.swf", 
      flashvars, params, attributes);

    jQuery("#interior_360").click(function(e){
      var model_name = jQuery(this).attr("data-model-name");
      if(jQuery(this).hasClass("360_hidden")){
        jQuery(this).html(model_name+" <span>Normal</span> View");
        jQuery(".model_image_area").hide();
        jQuery("#fast360holder").show();
        init_360();
      }else{
        jQuery(this).html(model_name+" <span>360&deg;</span> Interior View");
        jQuery(".model_image_area").show();
        jQuery("#fast360holder").hide();
      }
      jQuery(this).toggleClass("360_hidden");
      e.preventDefault();
    }); 
  }
});

function hotspot(message){
  //console.log(message);
}


/**** Accessories Choose *********/
$(document).ready(function() {
  $(".accessories_list .acc_group a:not(.sub a)").click(function(){
    $(".accessories_list .acc_group").removeClass("selected").find(".sub").hide();
    $(this).parent().toggleClass("selected").find(".sub").toggle();
    return false;
  });
  $(".accessories_list .sub a").click(function(){
    $(".accessories_detail").html("").addClass("ajax_loading");
    $.get("/vehicles/accessory_detail/"+$(this).attr("data-id")+"/"+$("#range_accessories_container").attr("data-range"),function(response){
      $(".accessories_detail").removeClass("ajax_loading");
      $(".accessories_detail").html(response);
      
      $(".accessory_add").click(function(){
    		var vname = jQuery(this).attr("data-accessory-name"), 
    				vpart = jQuery(this).attr("data-accessory-part"),
    				vprice = jQuery(this).attr("data-accessory-price"),
    				vstr = "name="+vname+"&part="+vpart+"&price="+vprice
    				;
        $("#config_form").append('<input type="hidden" name="configurator[accessories][]" value="'+vstr+'">');
        return false;
      });
      
    });
    return false;
  });
  
  
  
  $(".accessories_list .acc_group a").eq(0).click();
  $(".accessories_list .sub a").eq(0).click();
  
});

/**** Transmission Choose ******/
$(document).ready(function() {
  $("#auto_transmission_select").change(function(){
    $("#cf_base").val($(this).attr("data-price"));
    $("#cf_trasmission").val("Automatic");
  });
  
  $("#manual_transmission_select").change(function(){
    $("#cf_base").val($(this).attr("data-price"));
    $("#cf_trasmission").val("Manual");
  });
  
  $("#linear_transmission_select").change(function(){
    $("#cf_base").val($(this).attr("data-price"));
    $("#cf_trasmission").val("Lineartronic");
  });
  
});


/**** Save To My Subaru **********/
$(document).ready(function() {
  $(".save_current_car").click(function(){
    $(this).addClass("active");
    $.cookie("vehicle", $("#config_url").text(), {path: '/'});
    $(document).trigger("yoursubaru");
    $(this).removeClass("active");
    alert('Saved as your Vehicle');
    return false;
  });
  
  $("#send_car_dealer").overlay({ 
    expose: '#333', 
    onBeforeLoad: function() { 
       $.get("/vehicles/dealer_send/"+$("#config_url").text(),function(response){
         $("#dealer_send").append(response);
         $(document).trigger("address_lookup");
       });
    } 
  });
});


$(window).load(function() {
  if($("#cf_trigger").val() !=1) $("#cf_trigger").val(1);
});

$(document).ready(function() {
  $(".model_totals .dropdown_range li").each(function(){
    var imgsrc = $(this).attr("data-image");
    $(this).find("a").append("<img src='"+imgsrc+"'>");
  });
  
  $(".model_totals .dropdown_range li").eq(0).remove();
  
  $("#configure_rechoose").hover(
    function(){
      $(this).next(".dropdown_range").removeClass("hidden");
      $(this).parent().mouseleave(function(){$(this).find(".dropdown_range").addClass("hidden");});
    }
  );
  
  $("#configure_next").click(function(){
    $(".model_summary .tabs li .current").parent().next().find("a").click();
  });
  
});

/****** Preload Colour Images **********/
$(document).ready(function() {
  if($.browser.msie && $.browser.version < 8) {

  } else {
    var def_image = $(".model_image_area img").eq(0);
    $(".colour_swatch").each(function(){
      var images_to_preload = [
        $(this).attr("data-image-front"),
        $(this).attr("data-image-front-thumb"),
        $(this).attr("data-image-side-thumb"),
        $(this).attr("data-image-back-thumb"),
        $(this).attr("data-image-side"),
        $(this).attr("data-image-back")
      ];
      for(var i in images_to_preload){
        if(images_to_preload[i].length > 2){
          var img = def_image.clone();
          $("body").append(img);
          $(img).attr("src",images_to_preload[i]).css({"position":"absolute","z-index":3,visibility:"hidden",left:"-2000px"});
        }
      }
    });
  }
  $(document).trigger("colours_ready");
});

$(document).ready(function() {
  $('script[data-observed="config_form"]').bind("wax:complete", function(xhr){
    var share = $("#config_url").text();
    var sub_base_url = "http://subaru.co.uk/vehicles/share/";
    var twitter_base_url = "http://www.twitter.com/home?status=I Just Configured My Subaru - http://subaru.co.uk/vehicles/share/";
    $("a[name=fb_share]").attr("href", "http://facebook.com/sharer.php?u="+sub_base_url+share);
    $("a[name=twitter_share]").attr("href", twitter_base_url+share);
    $("#save_as_pdf").attr("href", "/vehicles/pdf/"+share);
    $("a.accessory-remove-link").unbind("click").click(function(){
      $("#config_form input[value="+$(this).attr("data-value-in-hidden-form")+"]").remove();
      return false;
    });
  });
  
});

$(document).ready(function(){
  if($.browser.msie && parseInt($.browser.version.charAt(0),10) < 8){
    $('.car_angle_button').each(function(){
      $(this).children().attr('style', 'margin-top: 0px !important; margin-left: -9px !important;');
    });
    $('.model_image_thumbnails .button').css('margin-top', '0px');
  }
});



$(document).ready(function() {
  $("#gallery .next, #gallery .prev").click(function(){return false;});
  
});


