(function() {

  var Globals = {};

  jQuery(document).ready(function() {
      // Load  the JSON for the album data, artistID comes from artist nav
      $.getJSON("/shared/carousel/CarouselService.aspx/GetDiscography?artistID=" + artistID, 
                function(json) {
                  //console.log("No. of albums : " + json.length);
                  var albums = json;
                  Globals.albums = albums;
		  if (Globals.albums.length > 0)
                    initCarousel();
		   else {
		     $('#coverprev span img').attr("src","/images/portal/carousel/empty150.gif");
		     $('#covernext span img').attr("src","/images/portal/carousel/empty150.gif");
		     $('#covercenter .image a img').attr("src","/images/portal/carousel/empty200.gif");
		     $('#covercenter .image a img').attr("alt","No releases found");
                     $("#covercenter .text ul").replaceWith("No Releases");
		   }

                });
    });

  function initCarousel() {
    jQuery('#mycarousel').jcarousel({
      size: Globals.albums.length,
          initCallback: function(carousel, state) {
          //console.log("Init callback");          
          
        //  console.log("Adding click handler to Go button");
        //  $('#change_style').click(function() {
            //TODO construct JSON feed URL from selected option
        //    console.log("Selected option is " + $('#style').val());
        //    $.getJSON("/shared/carousel/CarouselService.aspx/GetDiscography?artistID=92"),
        //    function(json) {
        //        console.log("reset carousel with new JSON");
        //        Globals.albums = json['albums'];
        //        carousel.reset(); 
        //       carousel.size(Globals.albums.length);
                //Setup initial transition
        //        topCarouselClickTransitions({
        //            "prev": carousel.size(),
        //              "current": 1,
        //              "next": 2
        //              });
        //    });

        //    return false;
        //  });
          
          carousel.size(Globals.albums.length);

          //Add event handlers to lower carousel
	  if (Globals.albums.length > 2)
          {		  
            $('#coverprev span#spancoverprev, #covernext span#spancovernext').click(function() {
              //Get image positions
              var img_pos = getNextPrev(parseInt($(this).attr('jcarouselindex')), carousel.size());

              //Change Carousel
              bottomCarouselClickTransitions(img_pos);

              //Move top carousel
              carousel.scroll(img_pos.current);
            });
	  }

          //Setup initial transition
          initialTransitions();
        },

          itemLoadCallback: function(carousel, state) {
          //console.log("Item Load callback : " + state);
          for (var i = carousel.first; i <= carousel.last; i++) {
            if (carousel.has(i))
              {
              }
            else
              {
                //console.log(i + " needs to be populated with " + getImageUrl(i, "thumb"));
                var innerHTML = '<img src="' + getImageUrl(i, "thumb") + '" alt=""/>';
                var elem = carousel.add(i, innerHTML);

                //Add event handler to click
		if (Globals.albums.length > 1) {
                  $(elem).click(function() {
                    var img_pos = getNextPrev(parseInt($(this).attr('jcarouselindex')), carousel.size());

                    topCarouselClickTransitions(img_pos);

                    //Shift Carousel if last image
                    //console.log("Size : %d, Last : %d, Current : %d, Visible : %d", carousel.size(), carousel.last, img_pos.current, carousel.options.visible);
                    if ((carousel.last != carousel.size()) && (carousel.last == img_pos.current))
                      carousel.next();

                    if (carousel.first != 1 && (carousel.first == img_pos.current))
                      carousel.prev();

                    return false;
                  });
		}
              }
          }
        }
      });
  }

  // Simple function to calculate the right index values for a circular carousel
  function getNextPrev(index, length) {
    var img_pos = {};
    img_pos.current = index;

    if (index == length) {
      if (length == 2)	    
        img_pos.next = 3;
      else
	img_pos.next = 1;
    }
    else
      img_pos.next = index + 1;

    if (index == 1) {
      if (length == 2) 
       img_pos.prev = length + 1;
      else
       img_pos.prev = length;
    }
    else
      img_pos.prev = index - 1;

    return img_pos;
  }

  // Get the URL of the image from the right tag
  function getImageUrl(index, size) {
    if (!Globals.albums[index-1])
	    return "/images/portal/carousel/empty150.gif";

    var img_parent_url = "/images/local/"
      switch (size) {
      case "thumb":
      return img_parent_url + "50/" + Globals.albums[index - 1]["Url"];
      break;
      case "medium":
      return img_parent_url + "150/" + Globals.albums[index - 1]["Url"];
      case "large":
      return img_parent_url + "200/" + Globals.albums[index - 1]["Url"];
      break;
      }
  }

  //Get the product page URL
  function getProductPageUrl(json) {
    return "/artist/releases/release.aspx?pid=" + json["ID"] + "&aid=" + json["PrimaryArtistID"];
  }

  //Get the review page URL
  function getReviewPageUrl(json) {
    return "/artist/releases/review.aspx?pid=" + json["ID"] + "&aid=" + json["PrimaryArtistID"] + "&cmnt=1";
  }

  // Get the identifier for the Div to load
  function getID(index) {
    return Globals.albums[index - 1]["ID"];
  }

  //Replaces the image with the album image pointed to by index
  function replaceImageUrl(xpath_img, index, size) {
    //Replace the src attribute of img tag
    $(xpath_img).attr('src', getImageUrl(index, size));
    //Set the jcarouselindex attribute to keep track of image index
    $(xpath_img).parent().attr('jcarouselindex', index);
  }


  //Replaces HTML content of DIV
  function replaceHtmlDiv(index, animation) {
    $.getJSON("/shared/carousel/CarouselService.aspx/GetProduct?artistID=" + getID(index), 
              function(json) {
                //console.log("Got response.." + json["title"]);
                //console.log("Artist URL : %s", getProductPageUrl(json));
                // Replace text
                $('#covercenter .text span').each(function(i) {
                    var dom_id = $(this).attr("id");
                    var json_id = dom_id.substring(8);
                    //console.log("dom_id : %d, json_id : %d, json_val : %s", dom_id, json_id, json[json_id]);
                    $(this).html(json[json_id].toString());

                  });
                // Replace hyperlinks
                $('.product_url').each(function() {
                  $(this).attr("href", getProductPageUrl(json));
                });
                
                $('.reviews_url').attr("href", getReviewPageUrl(json));
                
                //Replace alt text for images
                $('#covercenter .image a img').attr("alt", json["Title"]);
                $('#covercenter .image a img').attr("title", json["Title"]);
                
                animation();
              });
  }


  // Sequence of animations that happen when an image in the top carousel is clicked 
  function topCarouselClickTransitions(img_pos) {
    fadeOutAndReplace("#coverprev", "#coverprev span img", img_pos.prev, "medium");
    fadeOutAndReplace("#covernext", "#covernext span img", img_pos.next, "medium");
    fadeOutAndReplace("#covercenter", "#covercenter .image a img", img_pos.current, "large");
  }

  //Sequence of animations that happen right at the beginning
  function initialTransitions() {
	  if (Globals.albums.length == 1)
	  {
            fadeOutAndReplace("#covercenter", "#covercenter .image a img", 1, "large");
	    $('#coverprev span img').attr("src","/images/portal/carousel/empty150.gif");
            $('#covernext span img').attr("src","/images/portal/carousel/empty150.gif");
	  }
          else if (Globals.albums.length == 2)
	  {
            fadeOutAndReplace("#covercenter", "#covercenter .image a img", 1, "large");
	     $('#coverprev span img').attr("src","/images/portal/carousel/empty150.gif");
	     $('#covernext span img').attr("src","/images/portal/carousel/empty150.gif");
	  }
	  else
	  {
             topCarouselClickTransitions({
              "prev": Globals.albums.length,
              "current": 1,
              "next": 2
                });
	  }
 } 

  // Sequence of animations that happen when either the left/right image in the bottom carousel is clicked
  function bottomCarouselClickTransitions(img_pos) {
    slideLeftRight('#coverprev span#spancoverprev', '#coverprev span#spancoverprev img', img_pos.prev, "medium");
    slideLeftRight('#covernext span#spancovernext', '#covernext span#spancovernext img', img_pos.next, "medium");
    fadeOutAndReplace("#covercenter", "#covercenter .image a img", img_pos.current, "large");
  }

  // Fade out and replace effect for the bottom carousel.
  function fadeOutAndReplace(xpath_div, xpath_img, index, size) {
    $(xpath_div).fadeOut('slow', 
                         function() {
                           //Replace the image
                           replaceImageUrl(xpath_img, index, size);

                           //Replace HTML text if it is center div
                           if ($(xpath_img).parent().attr('class') == "product_url")
                             {
                               //console.log("Loading HTML for center DIV");
                               replaceHtmlDiv(index, 
                                              function() {
                                                $(xpath_div).fadeIn('slow');

                                              });
                             }
                           else
                             {
                               $(xpath_div).fadeIn('slow');

                             }
                         });
  }

  // Slide left-right effect for the bottom carousel
  function slideLeftRight(xpath_wrapper, xpath_img, index, size) {
    $(xpath_wrapper).animate({
      width: 'hide'
          },
      function() {
        //Replace the image
        replaceImageUrl(xpath_img, index, size);

        //Replace HTML text if it is center div
        if ($(xpath_img).parent().attr('class') == "product_url")
          {
            //console.log("Loading HTML for center DIV");
            replaceHtmlDiv(index, 
                           function() {
                             $(xpath_wrapper).animate({
                               width: 'show'
                                   });
                           });
          }
        else
          {
            $(xpath_wrapper).animate({
              width: 'show'
                  });
          }
      });
  }
 })();
