(function($) {
  $.fn.xtr = function(settings) {
    //handle: used as a base for determining JSON location
    var config = {
      racefile: "race.php", //used in creating URLs based on current component
      trailfile: "trail.php",
      handle: window.location.pathname.replace(/\.html/, ""),
      param: window.location.search,
      msgs: {
        description: '',
        specs: '',
        features: '',
		clicktoenlarge: ''
      },
      animate: !($.browser.msie && $.browser.version < 7)
    };
    
    $.extend(config, settings);

    var state = {
      display: "intro",
      group: null,
      type: null,
      product: null,
      types: null,
      xhr: null
    };

    var $xtr_text = $("#sidebar");
    var $apdiv = $("#main");
    var $bgimg = $("#bgImage");

    preloadImages();

    $("#parts").delegate(".clickable", "click", function() {
      state.group = $(this).attr("title");
      state.display = "group";
      //console.log(state);
      updateDisplay();
    });

/*
	$('#sub_nav_children').delegate('a', 'click', function(e) {
		var href = $(this).attr('href');
		if (href.indexOf(config.racefile) >= 0 || href.indexOf(config.trailfile) >= 0) {
			e.preventDefault();
			window.location.href = href + window.location.hash;
			return false;
		}
	});
*/

/*
    $("#system_trail").click(function (e) {
        //console.log("system trail");
        if (!isTrail()) {
              var url = window.location.href;
              window.location.href = url.split(config.racefile).join(config.trailfile);              
        } else {
              window.location.hash = "";
              window.location.reload(true);
        }
        e.preventDefault();
    });
    $("#system_race").click(function (e) {
        //console.log("system race");
        if (isTrail()) {
              var url = window.location.href;
              window.location.href = url.split(config.trailfile).join(config.racefile);                          
        } else {
              window.location.hash = "";
              window.location.reload(true);
        }
        e.preventDefault();
    });
*/
    

    function initState() {
      var hash = window.location.hash.substring(1);
      var labels = hash.split('/');

      if (notEmpty(labels)) {
        state.group = labels.shift();
        state.display = "group";
      }
      //TODO change to new group id
      if (notEmpty(labels)) {
        state.type = labels.shift();
        state.display = "group-type";
      }
      if (notEmpty(labels)) {
        state.product = labels.shift();
      }
    }

    function notEmpty(arr) {
      return arr.length > 0 && arr[0] != "";
    }

    function updateDisplay() {
      //console.log("updating display: " + state.display);
      
      
      switch (state.display) {
        case "intro":
          resetDisplay();
          window.location.hash = "";
          state.xhr = $.getJSON(config.handle + ".intro.json" + config.param, function(data) {
			displayIntro(data);
          });
          break;
        case "group":
          resetDisplay();
          window.location.hash = "#" + state.group;
          state.xhr = $.getJSON(config.handle + ".group." + state.group + ".json" + config.param, function(group) {
            state.types = group.types;
            displayGroup(group);
          });
          break;
          
        //occurs when a type is directly loaded from a hash.
        case "group-type":
          window.location.hash = "#" + state.group + "/" + state.type;
          state.xhr = $.getJSON(config.handle + ".group." + state.group + "." + state.type + ".json" + config.param, function(group) {
              
            //need to displayGroup() here
            
              
            state.types = group.types;
            displayGroup(group);
            displayType(group);
          });
          break;
          
        //occurs when the group is already loaded and the user clicks a type button
        case "type":
          
          window.location.hash = "#" + state.group + "/" + state.type;
          state.xhr = $.getJSON(config.handle + ".type." + state.group + "." + state.type + ".json" + config.param, function(type) {
            displayType({types: [type]});
          });
          break;

      }
    }

    function displayIntro(intro) {
      if (intro.bgImage) {
        setBgImage(intro.bgImage.url);
      }
      
      $xtr_text.append("<h1>" + intro.title + "</h1>").append("<br/>").append("<h3>" + intro.text + "</h3>");
      $apdiv.append($("<div/>",{width: "752px", height: "447px", id: "xtr_bike_flash"}));

      flashembed("xtr_bike_flash", {
		src: ctxPath + '/flash/cycle/xtr/xtr_bike.swf',
		wmode: 'transparent'
	  },{
		json: config.handle + '.flashjson.json' + config.param
      });
        
      showItems();
    }

    function displayGroup(group) {
      if (group.bgImage) {
        setBgImage(group.bgImage);
      }
      
      $("#parts img").each(function() {
        this.src = this.src.replace(/navOn/, "navOff");
        if (this.title == group.label) {
          this.src = this.src.replace(/navOff/, "navOn");
        }
      });

      $xtr_text.append("<h1>" + group.title + "</h1>").append("<br/>")
      .append("<h3>" + group.text + "</h3>").addClass("sidebar-group");

      $apdiv.addClass("group_slideshow"); //modified from .video
      
      var $img = $("<img/>",{id:'picture_slider',src: (group.media.length > 0 ? group.media[0].image : ''),width:"480px",height:"356px"})
      var $controls = $("<div/>").addClass("centerAligned");
      var $caption = $("<div/>",{id:"picture_slider_caption"}).addClass("centerAligned");
      
      
      
      $apdiv.delegate(".picture_slider_thumb", "click", function() {
        $(".picture_slider_thumb").removeClass("thumb_selected");
        $(this).addClass("thumb_selected");  
        var item = $(this).data('item');
        $("#picture_slider").attr("src",item.image);
        $("#picture_slider_caption").html(item.caption);
      });

      
      for (var i = 0; i < group.media.length && i < 6; i++) {
        $controls.append(
            $("<img/>",{src:group.media[i].thumb,width:"75px",height:"75px"}).addClass("picture_slider_thumb")
            .data('item',group.media[i])
        );   
      }
      $apdiv.append($img).append($caption).append($controls)
      .append("<br /><img style='float: left; padding-right: 5px' src='" + ctxPath + "/images/cycle/xtr/icon-enlarge.gif'><div style='padding-top: 4px;'>Click thumbnails to enlarge</div><div style='clear: both;'></div>");
      
      

      showItems();

      displayTypeNav();
      
      $(".picture_slider_thumb:first").click();
      
    }

    function displayType(group) {
      //console.log("displayType:" + state.type);
      //console.log(group);

      var tIdx = indexOf(group.types, "label", state.type);

      if (tIdx < 0) {
        alert("invalid type");
        return;
      }

      var type = group.types[tIdx];

      if (type.bgImage) {
        setBgImage(type.bgImage.url);
      } else if (group.bgImage) {
        setBgImage(group.bgImage);
      }
      
      //lightbox
      $("<a/>",{id:"popuptrigger",href:"#popup-lightbox"}).fancybox({
          'modal':true,
          'onComplete':function () {
              
            $("#fancybox-close").show();   
          }
      }).click();
      
      $("#popup_sidebar").empty().append("<h2>" +type.title+ "</h2>");
      

      var $accordion = $("<div/>", {id: "com_accordion", tabindex: 0})
      .appendTo("#popup_sidebar");
      
      $accordion.append(getAccordionPanel(config.msgs.description, "prd_desc"));
      $accordion.append(getAccordionPanel(config.msgs.specs, "prd_spec_table"));
      $accordion.append(getAccordionPanel(config.msgs.features, "prd_features"));

      $accordion.accordion({header: 'h3', autoHeight: false});

      //$apdiv.addClass("sku");
      
      $pmain = $("#popup_main");
      
      $pmain.empty();
      
      
      $("<img/>", {id: "largepicture"}).appendTo($pmain);
      
      $("#popup_enlarge").empty()
      .append(
        $("<span/>", {id: "click_to_enlarge"}).addClass("clickable")
        .click(function() {
          var i = new Image();
          i.src = $("#largepicture").attr("src").replace(/\.[0-9]+\.[0-9]+/, ".800.0");
          $(i).one("load", function() {
              //zIndex because we're using JQ fancyBox as well
            $(this).overlay({opacity: 0.95,zIndex: 1200});
          });
          if (i.complete) $(i).trigger("load");
        })
        .append($("<img/>", {src: ctxPath + "/images/cycle/xtr/clickto.png"})));

      var $prdlist = $("<div/>");
      var $toOpen = null;

      $("#popup_list").empty();
      
      for (p = 0; p < type.products.length; p++) {
        var product = type.products[p];
        if (product.productImage) {
          // preload all the product images
          var img = new Image();
          img.src = product.productImage.baseUrl + "480.0." + product.productImage.type;
        }

        var $a = $("<a/>", {href: "#" + product.code}).addClass("sku_link")
        .data("product", product)
        //.text(product.code)
        .click(function() {
          $(".sku_link").removeClass("sku_current");
          $(this).addClass("sku_current");
          displayProduct($(this).data("product"));
          return false;
        }).append($("<img />", {src: product.productImage.baseUrl + "80.0." + product.productImage.type,
        title: product.code}));

        
        if (product.code == state.product) {
          $toOpen = $a;
        }
        //need to make this an image instead
        $("#popup_list").append($a);
      }

      
      $("#popup_docs").append($("<div/>", {id: "sku_pdfs"}));

      if ($toOpen != null) $toOpen.click();
      else $(".sku_link:first").click();

      //showItems();
      //displayTypeNav();
    }

    function displayProduct(product) {
      state.product = product.code;
      window.location.hash = "#" + state.group + "/" + state.type + "/" + state.product;
      
      var img = product.productImage;
      if (img) {
        $("#largepicture").hide().attr("src", img.baseUrl + "480.0." + img.type);

        if (false && config.animate) {
            $("#largepicture").fadeIn(2000, function() {
                  $("#largerlink").show();
            });
        } else {
            $("#largepicture").show();
            $("#largerlink").show();
        }
      }

      //switch active trail / race buttons and bind click based on current state
      if (isTrail()) {
          $("#com_trail").addClass("com_trail_active").
          click(function(e) {
              e.preventDefault();
          });
          $("#com_race").removeClass("com_race_active").
          click(function() {
              var url = config.racefile + "#" + state.group + "/" + state.type;
              window.location.href = url;
          });
      } else {
          $("#com_race").addClass("com_race_active").
          click(function(e) {
              e.preventDefault();
          });
          $("#com_trail").removeClass("com_trail_active").
          click(function() {
              var url = config.trailfile + "#" + state.group + "/" + state.type;
              window.location.href = url;              
          });
          
      }
      
      
      $("#prd_desc").html(product.longDescription);

      var $specTable = $("<table/>", {
        cellspacing: 0,
        cellpadding: 0,
        border: 0
      });

      for (s = 0; s < product.specs.length; s++) {
        var spec = product.specs[s];
        var $tr = $("<tr/>").appendTo($specTable);
        $tr.append($("<td/>").addClass("name").text(spec.header));
        var values = "";
        for (v = 0; v < spec.values.length; v++) {
          values += " " + spec.values[v];
        }
        if (values.length == 0) values = "&nbsp;";
        $tr.append($("<td/>").html(values));
      }

      $("#prd_spec_table").html($specTable);

      var $features = $("#prd_features").empty();
      for (f = 0; f < product.features.length; f++) {
        var feature = product.features[f];
        if (feature.header.length > 0) {
          $("<h3/>").text(feature.header).appendTo($features);
        }
        var $list = $("<ul/>").appendTo($features);
        for (r = 0; r < feature.rows.length; r++) {
          $("<li/>").html(feature.rows[r]).appendTo($list);
        }
      }

      var $pdfs = $("#sku_pdfs").empty();
      for (d = 0; d < product.techDocs.length; d++) {
        var doc = product.techDocs[d];
        
        $pdfs.append(
            $("<div/>").addClass("skupdf").append(
            $("<a/>", {href: doc.path}).append(
            $("<img/>", {src: ctxPath + "/images/cycle/xtr/pdficon_large.gif"})))
            .append(
                $("<div/>").addClass("techdoc").append(
            $("<a/>", {href: doc.path}).text(doc.name))));
      }
    }

    function isTrail() {
        return window.location.href.indexOf(config.trailfile) >= 0;
    }
    
    function displayTypeNav() {
      var types = state.types;
      var $table = $("<table/>", {
        cellspacing: 0,
        cellpadding: 0,
        border: 0
      })
      .delegate(".clickable", "click", function() {
        state.display = "type";
        state.type = $(this).data("label");

        updateDisplay();
      });

      var $images = $("<tr/>", {
        id: "lower_images"
      }).appendTo($table);
      var $titles = $("<tr/>", {
        id: "lower_text"
      }).appendTo($table);

      for (i = 0; i < types.length; i++) {
        var t = types[i];

        // the top image row
        var $cell = $("<td/>").appendTo($images);
        if (t.productImage) {
          $("<img/>", {
            src: t.productImage.baseUrl + "90.0." + t.productImage.type
          })
          .addClass("clickable")
          .data("label", t.label)
          .appendTo($cell);
        }

        // the bottom text row
        $("<td/>").appendTo($titles).append(
          $("<span/>")
          .addClass("clickable")
          .data("label", t.label)
          .text(t.title));
      }

      $("<div/>", {
        id: "lower_menu"
      }).addClass("xtr_component_menu")
      .hide()
      .insertAfter($apdiv)
      .append($table).fadeIn(200);
    }

    function resetDisplay() {
      if (state.xhr && state.xhr.readyState) {
        state.xhr.abort();
        state.xhr = null;
      }
      
      $xtr_text.hide().empty().removeClass("sidebar-group");
      $apdiv.hide().empty();
      $("#lower_menu").hide().remove();
    }

    function setBgImage(src) {
      $bgimg.attr("src", src);
    }

    $.template('xtr-a-panel-tmpl', '<h3>${title}</h3><div id="${id}"></div>');

    function getAccordionPanel(title, id) {
      return $.tmpl('xtr-a-panel-tmpl', {title: title, id: id});
    }

    function indexOf(arr, field, value) {
      for (i = 0; i < arr.length; i++) {
        if (arr[i][field] == value) {
          return i;
        }
      }

      return -1;
    }

    function preloadImages() {

      $("#groups img").each(function() {
        i = new Image();
        i.src = this.src.replace(/navOff/, "navOn");
      });
    }

    function showItems() {
      $xtr_text.fadeIn(500);
      $apdiv.fadeIn(500);
    }
    
    initState();
    updateDisplay();
    
    if (!config.animate) {
        $(window).resize(function() {
            $("#scroll_wrap").css("height", 
                $(document.body).height() -
                $("#header").height() -
                $("#footer").height());
        });

        $(window).resize();
    }
   
  }
})(jQuery);
