// Jquery slider-gallery code.
$(window).ready(function () {

  $("a#openLongDescInline").fancybox({
    'padding': 0,
    'margin': 25,
    'overlayColor': '#000'
  });

  $('.sliderItems').each(function() {
      bindImageChangeEvent(this.id);
  });

  $(".carousel").jCarouselLite({
      btnNext: ".next",
      btnPrev: ".prev",
      circular: false,
      visible: 6
  });
  bindImageClickEvent();

  $(".external").click(function () {

      // If we don't have the manufacture id then we don't do anything.
      if (manufacturerId == '') {
          return true;
      }

      // Send an jax request to log the click.
      $.ajax({
          type  : "POST",
          url   : statslogUrl,
          data  : 'data[ExternalLinkStatistic][link]=' + this.href + '&data[ExternalLinkStatistic][model_id]=' + manufacturerId + '&data[ExternalLinkStatistic][model_name]=Manufacturer',
          async : false
      });

      return true;
  });

  // shows and hides and toggles the slickbox on click
  $('#manf_slick-show').click(function() {
    $('#slickbox').slideDown('slow');
    $('#header_section_title').slideDown('fast');
    $('#logo').css('padding-bottom','10px');
    $('#toggle_close').slideDown('slow');
    $('.slickboxClosedHeader').slideUp('fast');
    $('#toggle_open').slideUp('fast');

    // Ajax request to set write the status in the session
    $.get(baseUrl + 'manufacturers/setSlickboxStatus/open');
    return false;
  });
  $('#manf_slick-hide').click(function() {
    $('#slickbox').slideUp('fast');
    $('#header_section_title').slideUp('fast');

    $('.slickboxClosedHeader').slideDown('slow');
    $('#toggle_close').slideUp('fast');
    $('#toggle_open').slideDown('slow');

    // Ajax request to set write the status in the session
    $.get(baseUrl + 'manufacturers/setSlickboxStatus/close');
    return false;
  });
  $('#slick-toggle').click(function() {
    $('#slickbox').toggle(400);
    return false;
  });

  $('#productListTab').click(function()
  {
      $('#carouselDiv').hide();
      $('#productListDiv').show();
      $('.overviewDiv').hide();
    return false;
  });

  $('#overviewTab').click(function()
  {
      $('#carouselDiv').show();
      $('#productListDiv').hide();
      $('.overviewDiv').show();
    return false;
  });

  //Empty the previous content
  $("#profile_slideshow").html('');

  $("#profile_slideshow").showcase({
      images: eval(profileProducts),
      width: "600",
      height: "360",
      border: "solid #fff 1px",
      animation: { autoCycle: true,
          type: "fade",
          interval: 3500,
          easefunction: "linear",
          speed: 1000 },
      navigator: {
          position: "bottom-right",
          showMiniature: true,
          autoHide: true,
          item: {
              css:     {
                      width: "44px",
                      height: "28px",
                      borderColor:"#ccc",
                      margin: "1px",
                      "-moz-border-radius": "0px",
                        "-webkit-border-radius": "0px"
                      },
                cssHover: {
                  backgroundColor: "#ddd",
                  borderColor: "#000" },
              cssSelected: {
                  backgroundColor: "#fff",
                  borderColor: "#fff" }
              }
          },
      titleBar: {
              enabled: true,
            css:     {
        width: "0px",
        height: "0px",
        backgroundColor: "transparent"
          }
      }
  });
  $("#subBar").css({ position: ""});

  // call the event to change the image caption
  setInterval( function() {

             // get image alt text which is the combination of caption and photographer name
             var combined = $("#subBar span").html();

             // Wait till page loads
             if (!combined)
             {
                 return;
             }

             // seperate the caption and photographer name
             var splited = combined.split("$#$");

             if (splited.length > 1) {
                 // Form the div containing caption and photographer name in two lines
                 contDiv = '<div>' + splited[0] + '<br>' + splited[1] + '</div>';
                 // transfer the changing alt text from subBar to subBar2
                 $("#subBar2 span").html(contDiv);
             } else {
                 // transfer the changing alt text from subBar to subBar2
                 $("#subBar2 span").html(splited[0]);

             }

             // Unbind all the click events
             $('#slider a').unbind('click');

             // Bind click event on images
             $('#slider a'). click(function()
             {
                     // If link is to be open in iframe then open in thickbox
                  if (-1 != this.href.search('iframe')) {
                      $.fancybox({
                            'title'			: this.title,
                            'width'		    : 550,
                            'height'		: 550,
                            'padding': 0,
                            'margin': 25,
                            'overlayColor': '#000',
//                            'transitionIn': 'elastic',
//                            'transitionOut': 'elastic',
                            'href'			: this.href,
                            'type'			: 'iframe'
                        });
                        return false;
                  }
             });
          }, 1000);

});

function trackThickbox(url, slot, key, value) {
    try {
        _gaq.push(['_setCustomVar', slot, key, value, 3]);
        _gaq.push(['_trackPageview', url]);
    } catch (e) { }
}

// Function to attach the image change event.
function bindImageChangeEvent(productId)
{
    // If the user clicks on a product image in the carousel ..
    $('#' + productId).click(function()
    {
        // Get the product id
        var prodId = productId.replace('product_','');

        // Change the main image source so it appears
        $('#mainImage').attr('src', $('#'+ productId).attr('href'));

        // Display the content in the div from at alt attrib
        $('#manufactureprofile_pic_short_desc').html($('#image_'+ prodId).attr('alt'));

        // If the hidden field has no valye i.e for details link simply hide it.
        if ($('#productLink_'+ prodId).val() == '') {
            $('#onlyImage').remove();
            $('#productLink').hide();

            // We will show the image only and will not attach link to it when product does not have any url
            // Prepare image string to be shown
            var productImage = '<img src="' + $('#mainImage').attr('src') + '" id="onlyImage" alt="" border="0">';

            // Display image
            $('#ImageproductLink').after(productImage);

            // Hide the image with link html
            $('#ImageproductLink').hide();
        } else {
            // Get the link url.
            var linkUrl = $('#productLink_'+ prodId).val();

            // Hide only image html, which gets shown when product does not have any url
            $('#onlyImage').remove();
            // Set the href attrib
            $('#productLink').attr('href', linkUrl);
            $('#ImageproductLink').attr('href', linkUrl);

            // It can be hidden due to last click show it anyway
            $('#productLink').show();
            $('#ImageproductLink').show();

            // Since we change the url of the 'Details>>' link we need to set / unset the attributes
            var extra = $('#productLink_'+ prodId).attr('extra');

            // If its a url remove the chickbox class
            if (extra == 'url') {
                $('#productLink').unbind('click');
                $('#productLink').attr('target', '_blank');

                $('#ImageproductLink').unbind('click');
                $('#ImageproductLink').attr('target', '_blank');
            } else if (extra == 'thickbox') {
                // populate the long description if any
                var longDesc = $('#productLink_'+ prodId).attr('longdesc');
                $('#product_long_desc').html('<p>' + longDesc + '</p>');

                // Its the long description
                $('#productLink').removeAttr('target');
                //Shadowbox.init('#productLink');

                $('#ImageproductLink').removeAttr('target');
                //tb_init('#ImageproductLink');
            } else {
                // Its the pdf do not have any attributes
                $('#productLink').removeAttr('target');
                $('#productLink').unbind('click');

                $('#ImageproductLink').removeAttr('target');
                $('#ImageproductLink').unbind('click');
            }
            bindImageClickEvent();
        }

        $.get(baseUrl + 'products/log_access/' + prodId);

        return false;
    });


}

// Function called when image link is clicked
function bindImageClickEvent()
{
    $('#ImageproductLink').click(function()
    {
        // If the link url and current url is same then no need to proceed further
        if (this.href == window.location) {
            return false;
        }
  });

}
