
$j = jQuery;

$j(document).ready(function(){
  
  /* Create negative margins for promo banners 
  placeBanners();
  $j(window).resize(placeBanners);
  
  function placeBanners() {
    var docWidth = $j('#page').width();
    
    if(docWidth < 1220){
      newMargin = ((1220 - docWidth)/2) * (-1);
    
      $j('#skullcandy-left').css({'left': newMargin });
      $j('#skullcandy-right').css({'right': newMargin });
    } else {
      $j('#skullcandy-left').css({'left': 0 });
      $j('#skullcandy-right').css({'right': 0 });
    }
  }
  */
  $j('input[name=CampaignList_37578]').attr('checked', true);
  
  randomnum = Math.floor(Math.random()*4);
  $j('#homepage-promo').addClass('v' + randomnum);
  
  /* Controls All Items / Top 20 tab highlighting */
  
  $j('#top20-tab a').mouseover(function() {
    $j('#all-tab a').removeClass('active');
  });
  
  if ($j('#top20-tab a').attr('href')) {
    $j('#top20-tab a').mouseout(function() {
      if (!$j('#all-tab a').attr('href')) {
        $j('#all-tab a').addClass('active');
      }
    });
  }
  
  $j('#all-tab a').mouseover(function() {
    $j('#top20-tab a').removeClass('active');
  });
  
  if ($j('#all-tab a').attr('href')) {
    $j('#all-tab a').mouseout(function() {
      if (!$j('#top-tab a').attr('href')) {
        $j('#top20-tab a').addClass('active');
      }
    });
  }
  
  /* Disable right click menu
  $(document).bind("contextmenu",function(e){
    return false;
  });*/
  
  $j('.shop-product-small .retail-label').each(function(){
    if ($j(this).children('.retail-price').html()) {
      $j(this).removeClass('invisible');
    };
  });
  
  populateElement('#shop-nav .product-form input#CAT_ProductSearch', 'Search products...');
  
  // "Open" and "Close" comments form
  $j('.comment-form').hide();

	// Hide a show comment form
	$j('a.write-review, a.close-link').click(function(){
		$j('.comment-form').slideToggle('slow');
	});

  // Change out ratings stars
  if ($j('.rating img').attr('alt') == '2 out of 5 stars') {
    $j('.rating img').attr('src', '');
  }
  
  // Set menus items based on path
  var pathname = window.location.pathname;
  //var url = window.location;
  
  // Sets primary nav Shop item to selected
  $j('div#shop, ul.productList').each(function(){   
    $j('li#shop').addClass('selected');
  });
  
  if(pathname.indexOf('OrderRetrievev2.aspx') != -1) {
    var shippingOptions = document.getElementById('ShippingOptions');
    
    /*if (shippingOptions) {
      if (shippingOptions.length > 2) {
       shippingOptions.selectedIndex = 2;
      } else {
       shippingOptions.selectedIndex = 1;
      }
      shippingOptions.onchange();
    }*/
    
    $j('#BillingAddress').each(function(){
      SetBilling(1);
    });
    
    $j('#shippingCalc input').each(function(){
      $j(this).removeAttr("checked"); 
    });
    
    /* Remove alerts 
    window.alert = function(msg){
      $j('.actions').append(msg);
      if (msg == 'Shipping option selected successfully.') {
       return false;
      } else {
       alert(msg);
      }
    }*/
    
    //var addedHtml = '<input type="hidden" value="' + url + '" />';
    //$j('#FirstName').after(addedHtml);
    
    //tmx_setup();
    
  }
  
  // Sets Skullcandy Shop Pages
  if(pathname.indexOf('skullcandy-apparel') != -1) {
    $j('#top20-tab a').addClass('active');
  }
  
  // Sets Skullcandy Shop Pages
  if(pathname.indexOf('brands/skullcandy') != -1) {
    $j('#all-tab a').addClass('active');
  }
  
  
  // Sets primary nav Shop item to selected
  if(pathname.indexOf('_blog') != -1) {
    $j('li#blog').addClass('selected');
  }
  
  // Implement progressive loading with Lazy Loader on catalog pages and search results
  if(pathname.indexOf('_catalog') != -1 || pathname.indexOf('Default.aspx') != -1) {
    $j(".productList .shop-product-small .image img").lazyload({
      placeholder: '/templates/images/white.gif',
      effect: 'fadeIn'
    });
  }  
  link = '';
  css_class = '';
  
  //pathname = pathname.replace(/-/i, ' ');
  //pathname = pathname.replace('/', ' ');
  
  //alert(pathname);
  
  // Insert brand logos on product pages
  $j('.shop-product-large').each(function(){    
    if(pathname.indexOf('wesc') != -1) {
      link = '/brands/wesc';
      css_class = 'wesc';
    }
    if(pathname.indexOf('skullcandy') != -1) {
      link = '/brands/skullcandy';
      css_class = 'skullcandy';
      $j('body').addClass('skullcandy');
      $j('.skullcandy-dealer').removeClass('invisible');
      $j('.skullcandy-warranty').removeClass('invisible');
      $j('.quantity img').attr('src', '/templates/images/skullcandy/btn-buy-now.png');
      $j('.sk-featured').addClass('hidden');
    }
    
    if(pathname.indexOf('aiaiai') != -1) {
      link = '/brands/aiaiai';
      css_class = 'aiaiai';
    }
    if(pathname.indexOf('beats') != -1 || pathname.indexOf('heartbeats') != -1) {
      link = '//brands/beats-by-dre';
      css_class = 'beats';
      $j('.monster-dealer').removeClass('invisible');
    }
    if(pathname.indexOf('monster') != -1) {
      link = '/brands/monster';
      css_class = 'monster';
      $j('.monster-dealer').removeClass('invisible');
    }
    if(pathname.indexOf('matix') != -1) {
      link = '/brands/matix';
      css_class = 'matix';
    }
    if(pathname.indexOf('aerial7') != -1) {
      link = '/brands/aerial7';
      css_class = 'aerial7';
    }
    if(pathname.indexOf('urbanears') != -1) {
      link = '/brands/urbanears';
      css_class = 'urbanears';
    }
    if (link != '' && css_class != '') {
      $j('#product-logo').html('<a href="' + link + '">See more</a><div><a href="' + link + '" class = "logo-image ' + css_class + '"></a></div>');
    }
  });
  
  // Expand footer to fill window
  expandFooter();
  $j(window).resize(expandFooter);
 
  function expandFooter() {
    var docHeight = $j('#page').height();
   
    if(docHeight < $j(window).height()){
      $j('#footer').css({'height': $j('#footer').height() + ($j(window).height() - docHeight)});
    }   
  }
  
});

$(window).load(function(){
    
  //Format Homepage blog entries
  $j('.latest-blogs .blog-post').each(function(){
    
    blog_url = $j('.post-title a', this).attr('href');
    $j(this).html($j(this).html().replace('<script type="text/javascript" src="http://tweetmeme.com/i/scripts/button.js"></script>',''));       
    $j(this).html('<div class="post-image invisible"><a href="' + blog_url + '"><img src="' + $j('.post-body img', this).attr('src') + '"/></a><div class="clear"></div></div>' + $j(this).html());
    
    $j('.post-image img', this).sizeImage(158,200);
    $j('.post-body .links', this).html('');
    $j('.post-body', this).stripTags();
    $j('.post-body', this).html(truncateStr($j('.post-body', this).html(), 110, '...') + '<div class="clear"></div>');
  });

  $j('.latest-blogs').removeClass('invisible');
  
  // Adjust click functionality of Poplet thumbnails
  $j('.productPopletsItem a').attr('onclick', '');
  
  $j('.productPopletsItem a').click(function(event){
    $j('.shop-product-large .image').addClass('invisible');
    
    // Original Lightbox
    //$j('#lrg-image').html('<a href="' + $j(this).attr('href') + '" rel="' + $j(this).attr('rel') + '" onclick="myLightbox.start(this); return false;"><img src="' + $j(this).attr('href') + '"/></a>');  
    
    $j('#lrg-image').html('<a href="' + $j(this).attr('href') + '"><img src="' + $j(this).attr('href') + '"/></a>');
    
    // On image load, resize
    $j('#lrg-image img').load(function(){
      
      // Add magnification / zoom plugin
      if(window.location.href.indexOf('Gift_Certificate') == -1) {    
        $j(this).magnify();
      }
      
      $j(this).sizeImage(320,360);
      
      // Vertically align image
      topMargin = (360 - $j(this).height()) / 2;
      $j(this).css({ margin:topMargin + "px" });

    });
    
    return false;
  }); 
  
  // Resize product images
  $j('#lrg-image img').each(function(){
    if(window.location.href.indexOf('Gift_Certificate') == -1) {    
      $j(this).magnify();
    }
    
    $j(this).sizeImage(320,360);
    
  // Vertically align large image
  topMargin = (360 - $j(this).height()) / 2;
    $j(this).css({ margin:topMargin + "px" });    
  });
  
  // Vertically align thumbnail images
  $j('.productPopletsItem img').each(function(){
    topMargin = (50 - $j(this).height()) / 2;
    $j(this).css({ margin:topMargin + "px 0 0 0" }); 
  });
  
  // Replaces Product Top Section rating stars with custom icons
  $j('.shop-product-large .rating img').each(function(){
    var pathname = window.location.pathname;
    
    if(pathname.indexOf('skullcandy') != -1) {
     image_path = 'templates/images/skullcandy';
    } else {
     image_path = 'templates/images';
    }
    
    src = $j(this).attr('src').replace('CatalystImages', image_path);
    $j(this).attr('src', src);
    
    $j(this).css({ width:104 + "px" });
    $j(this).css({ height:21 + "px" });
    
    $j(this).load(function(){
      $j('.rating').removeClass('invisible');
    });
  });
  
  // Replaces Comments section rating stars with custom icons
  $j('.comments .rating img').each(function(){
    src = $j(this).attr('src').replace('CatalystImages', image_path);
    $j(this).attr('src', src);
    
    $j(this).css({ width:80 + "px" });
    $j(this).css({ height:16 + "px" });
    
    $j(this).load(function(){
      $j('.rating').removeClass('invisible');
    });
  });
  
  // Removes time from Comment dates
  $j('.comment-container .date').each(function(){ 
    $j(this).html($j(this).html().substr(0,$j(this).html().length - 8));
    $j(this).removeClass('invisible');
  });

  // Inserts empty message for Comments section
  if ($j('.all-comments').html() == '') {
    $j('.all-comments').html('<h3>Do you have this product?</h3><h5>Share your experience and be first to write a review.<h5>');
  }
  
  // Resizes Similar Products images
  //$j('.productList .shop-product-small .image img').each(function(){ $j(this).removeClass('invisible'});
  $j('.similar-products .shop-product-small .image img').each(function(){ 
    $j(this).sizeImage(100,150) 
    $j('.similar-products').removeClass('invisible');
  });
  
  // Change behavior for Product Swapping drop down
  $j('li.quantity .productSelectInput').attr('onchange', '');
  
  $j('li.quantity .productSelectInput').bind('change', function(){
    location.href = '/CatalogueRetrieve.aspx?&ProductID=' + $j(this).val() + '&Gift_Certificate';
  });
  
  $j('#ShippingAddress, #ShippingCity, #ShippingZip').bind('change', function(){
    SetBilling(1);
  });

});


/** FUNCTIONS **/

// Strip HTML tags
$j.fn.stripTags = function() { return this.html(this.html().replace(/<\/?[^>]+>/gi, '')); };

// Resizes image to max height / width
$j.fn.sizeImage = function(maxWidth, maxHeight) {

  var ratio = 0;  // Used for aspect ratio
  var width = $j(this).width();    // Current image width
  var height = $j(this).height();  // Current image height
  
  // Check if the current width is larger than the max
  if(width > maxWidth){
    ratio = maxWidth / width;   // get ratio for scaling image
    $j(this).css("width", maxWidth); // Set new width
    $j(this).css("height", height * ratio);  // Scale height based on ratio
    height = height * ratio;    // Reset height to match scaled image
    width = width * ratio;    // Reset width to match scaled image
  }
  
  // Check if current height is larger than max
  if(height > maxHeight){
    ratio = maxHeight / height; // get ratio for scaling image
    $j(this).css("height", maxHeight);   // Set new height
    $j(this).css("width", width * ratio);    // Scale width based on ratio
    width = width * ratio;    // Reset width to match scaled image
  }
  
  $j('.image').removeClass('invisible');
  $j('.post-image').removeClass('invisible');
}

function truncateStr(text, length, ellipsis) {    
  // Set length and ellipsis to defaults if not defined
  if (typeof length == 'undefined') var length = 100;
  if (typeof ellipsis == 'undefined') var ellipsis = '...';

  // Return if the text is already lower than the cutoff
  if (text.length < length) return text;
  
  for (var i = length-1; text.charAt(i) != ' '; i--) {
      length--;
  }

  // The for() loop ends when it finds a space, and the length var
  // has been updated so it doesn't cut in the middle of a word.
  return text.substr(0, length) + ellipsis;
}

function populateElement(selector, defvalue) {
    if($j.trim($j(selector).val()) == "") {
        $j(selector).val(defvalue);
    }
    $j(selector).focus(function() {
        if($j(selector).val() == defvalue) {
            $j(selector).val("");
        }
    });
    $j(selector).blur(function() {
        if($j.trim($j(selector).val()) == "") {
            $j(selector).val(defvalue);
        }
    });
}

function SetShipping(checked) {
	if (checked) {
		document.getElementById('ShippingAddress').value = document.getElementById('BillingAddress').value; 
		document.getElementById('ShippingCity').value = document.getElementById('BillingCity').value; 

		/*if (document.getElementById('BillingState').value == '') {
		  $j('#shipping-state').html('<label>State</label><br /><input type="text" class="cat_textbox" id="ShippingState" maxlength="255" name="ShippingState" />');
		} else {
		  document.getElementById('ShippingState').value = document.getElementById('BillingState').value; 
		}*/
		
		/*if (document.getElementById('BillingZip').value == '') {
		  $j('#shipping-zipcode').html('<label>Zipcode/Postcode</label><br /><input type="text" name="BillingZip" maxlength="255" id="ShippingZip" class="cat_textbox"/>');
		} else {
		  document.getElementById('ShippingZip').value = document.getElementById('BillingZip').value;
		}*/
		//document.getElementById('ShippingCountry').value = document.getElementById('BillingCountry').value; 
	} else {
		document.getElementById('ShippingAddress').value = ''; 
		document.getElementById('ShippingCity').value = ''; 
		//document.getElementById('ShippingState').value = ''; 
		//document.getElementById('ShippingZip').value = ''; 
		//document.getElementById('ShippingCountry').value = '';
	}
}

function SetBilling(checked) {
	if (checked) {
		document.getElementById('BillingAddress').value = document.getElementById('ShippingAddress').value; 
		document.getElementById('BillingCity').value = document.getElementById('ShippingCity').value; 

		if (document.getElementById('ShippingState').value == '') {
		  $j('#billing-state').html('<label>State</label><br /><input type="text" class="cat_textbox" id="BillingState" maxlength="255" name="BillingState" />');
		} else {
		  document.getElementById('BillingState').value = document.getElementById('ShippingState').value; 
		}
		
		if (document.getElementById('ShippingZip').value == '') {
		  $j('#billing-zipcode').html('<label>Zipcode/Postcode</label><br /><input type="text" name="BillingZip" maxlength="255" id="BillingZip" class="cat_textbox"/>');
		} else {
		  document.getElementById('BillingZip').value = document.getElementById('ShippingZip').value;
		}
		document.getElementById('BillingCountry').value = document.getElementById('ShippingCountry').value; 
	} else {
		document.getElementById('BillingAddress').value = ''; 
		document.getElementById('BillingCity').value = ''; 
		document.getElementById('BillingState').value = ''; 
		document.getElementById('BillingZip').value = ''; 
		//document.getElementById('BillingCountry').value = '';
	}
}
