/*
  Supersized - Fullscreen Background jQuery Plugin
  Version 3.1.3 Core
  www.buildinternet.com/project/supersized
  
  By Sam Dunn / One Mighty Roar (www.onemightyroar.com)
  Released under MIT License / GPL License
*/

(function($){

  //Add in Supersized elements
  $(document).ready(function()
  {
    // under ie9
    if(!Modernizr.backgroundsize)
    {
      //$('#bg').remove();
      $('body').append('<div id="supersized"></div>');
      $.supersized({
        slideshow : 0,
        autoplay : 0,
        start_slide : 0,
        slide_interval : 10000000,
        transition : 0,
        transition_speed : 750,
        new_window : 0,
        pause_hover : 0,
        keyboard_nav : 0,
        performance : 3,
        min_width : 0,
        min_height : 0,
        vertical_center : 0,
        horizontal_center : 1,
        fit_portrait : 0,
        fit_landscape : 0,
        navigation : 0,
        thumbnail_navigation : 0,
        slide_counter : 0,
        slide_captions : 0,
        image_protect: 1,
        slides:[{image:'/media/templates/bg.jpg'}]
      });
    }
  });
  
  //Resize image to fill background
  $.supersized = function( options ) {
    
    //Default settings
    var settings = {
          start_slide        :  1,    //Start slide (0 is random) //Requires multiple background images
      vertical_center         :   1,    //Vertically center background
      horizontal_center       :   1,    //Horizontally center background
      min_width            :   0,    //Min width allowed (in pixels)
      min_height            :   0,    //Min height allowed (in pixels)
      fit_portrait           :   0,    //Portrait images will not exceed browser height
      fit_landscape      :   0,    //Landscape images will not exceed browser width
      image_protect      :  1    //Disables image dragging and right click with Javascript
      };
    
    var element = $('#supersized');    //Define element for Supersized
    
    //Combine options with default settings
    if (options) {
      var options = $.extend(settings, options);  //Pull from both defaults and supplied options
    }else{
      var options = $.extend(settings);      //Only pull from default settings    
    }  
    
    //Determine starting slide (random or defined)
    if (options.start_slide){
      var currentSlide = options.start_slide - 1;  //Default to defined start slide
    }else{
      var currentSlide = Math.floor(Math.random()*options.slides.length);  //Generate random slide number
    }
    
    $("<img/>").attr("src", options.slides[currentSlide].image).appendTo(element);    //Set current image
    
    element.hide();    //Hide image to be faded in
    
    //Account for loading in IE
    $(document).ready(function() {
      resizenow();
    });
    
    //Display image once page has loaded
    $(window).load(function(){
    
      $('#supersized-loader').hide();    //Hide loading animation
      element.fadeIn('fast');        //Fade in background
      
      resizenow();
      
    });
    
    //Adjust image when browser is resized
    $(window).resize(function(){
        resizenow();
    });
  
    //Adjust image size
    function resizenow() {
      return element.each(function() {
        
          var t = $('img', element);
          
          //Resize each image seperately
          $(t).each(function(){
            
          var ratio = ($(this).height()/$(this).width()).toFixed(2);  //Define image ratio
          thisSlide = $(this);
          
          //Gather browser size
          var browserwidth = $(window).width();
          var browserheight = $(window).height();
          var offset;
          
          
          /**Resize image to proper ratio**/
          
          if ((browserheight <= options.min_height) && (browserwidth <= options.min_width)){  //If window smaller than minimum width and height
          
            if ((browserheight/browserwidth) > ratio){
              options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight(true);  //If landscapes are set to fit
            } else {
              options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth(true);    //If portraits are set to fit
            }
          
          } else if (browserwidth <= options.min_width){    //If window only smaller than minimum width
          
            if ((browserheight/browserwidth) > ratio){
              options.fit_landscape && ratio <= 1 ? resizeWidth(true) : resizeHeight();  //If landscapes are set to fit
            } else {
              options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth(true);    //If portraits are set to fit
            }
            
          } else if (browserheight <= options.min_height){  //If window only smaller than minimum height
          
            if ((browserheight/browserwidth) > ratio){
              options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight(true);  //If landscapes are set to fit
            } else {
              options.fit_portrait && ratio > 1 ? resizeHeight(true) : resizeWidth();    //If portraits are set to fit
            }
          
          } else {  //If larger than minimums
          
            if ((browserheight/browserwidth) > ratio){
              options.fit_landscape && ratio <= 1 ? resizeWidth() : resizeHeight();  //If landscapes are set to fit
            } else {
              options.fit_portrait && ratio > 1 ? resizeHeight() : resizeWidth();    //If portraits are set to fit
            }
            
          }
          
          /**End Image Resize**/
          
          
          /**Resize Functions**/
          
          function resizeWidth(minimum){
            if (minimum){  //If minimum height needs to be considered
              if(thisSlide.width() < browserwidth || thisSlide.width() < options.min_width ){
                if (thisSlide.width() * ratio >= options.min_height){
                  thisSlide.width(options.min_width);
                    thisSlide.height(thisSlide.width() * ratio);
                  }else{
                    resizeHeight();
                  }
                }
            }else{
              if (options.min_height >= browserheight && !options.fit_landscape){  //If minimum height needs to be considered
                if (browserwidth * ratio >= options.min_height || (browserwidth * ratio >= options.min_height && ratio <= 1)){  //If resizing would push below minimum height or image is a landscape
                  thisSlide.width(browserwidth);
                  thisSlide.height(browserwidth * ratio);
                } else if (ratio > 1){    //Else the image is portrait
                  thisSlide.height(options.min_height);
                  thisSlide.width(thisSlide.height() / ratio);
                } else if (thisSlide.width() < browserwidth) {
                  thisSlide.width(browserwidth);
                    thisSlide.height(thisSlide.width() * ratio);
                }
              }else{  //Otherwise, resize as normal
                thisSlide.width(browserwidth);
                thisSlide.height(browserwidth * ratio);
              }
            }
          };
          
          function resizeHeight(minimum){
            if (minimum){  //If minimum height needs to be considered
              if(thisSlide.height() < browserheight){
                if (thisSlide.height() / ratio >= options.min_width){
                  thisSlide.height(options.min_height);
                  thisSlide.width(thisSlide.height() / ratio);
                }else{
                  resizeWidth(true);
                }
              }
            }else{  //Otherwise, resized as normal
              if (options.min_width >= browserwidth){  //If minimum width needs to be considered
                if (browserheight / ratio >= options.min_width || ratio > 1){  //If resizing would push below minimum width or image is a portrait
                  thisSlide.height(browserheight);
                  thisSlide.width(browserheight / ratio);
                } else if (ratio <= 1){    //Else the image is landscape
                  thisSlide.width(options.min_width);
                    thisSlide.height(thisSlide.width() * ratio);
                }
              }else{  //Otherwise, resize as normal
                thisSlide.height(browserheight);
                thisSlide.width(browserheight / ratio);
              }
            }
          };
          
          /**End Resize Functions**/
          
          
          //Horizontally Center
          if (options.horizontal_center){
            $(this).css('left', (browserwidth - $(this).width())/2);
          }
          
          //Vertically Center
          if (options.vertical_center){
            $(this).css('top', (browserheight - $(this).height())/2);
          }
          
        });
        
        //Basic image drag and right click protection
        if (options.image_protect){
          
          $('img', element).bind("contextmenu",function(){
            return false;
          });
          $('img', element).bind("mousedown",function(){
            return false;
          });
        
        }
        
        return false;
        
      });
    };
    
  }; //End Supersized

  
})(jQuery);








// Addthis Twitter Template
var addthis_share = { templates: { twitter: '{{title}} {{url}} via @getplenty' } };

$(function()
{
  // home banner
  if($('.home-banner').length)
  {
    $('.home-banner .item').each(function()
    {
      var img = $('img',this).attr('src');
      if($(this).parents('.home-banner').hasClass('home-store-featured'))
      {
        $('.img',this).css({background:'url("'+img+'") 50% 20% no-repeat'});
      }
      else if($(this).parents('.home-banner').hasClass('lookbook-featured'))
      {
        $('.img',this).css({background:'url("'+img+'") 50% 30% no-repeat'});
      }
      else
      {
        $('.img',this).css({background:'url("'+img+'") 50% 50% no-repeat'});
      }
    });
  }
  
  // newsletter
  if($('#newsletter').length)
  {
    $('#newsletter .item').click(function()
    {
      $('.newsletter-box').slideDown(300);
    });
    
    $('.newsletter-box .close-btn').click(function()
    {
      $('.newsletter-box').slideUp(300);
    });
  }
  
  // search button
  $('.search-btn').click(function(e)
  {
    e.preventDefault();
    $(this).next().show(300);
  });
  
  // search action change
  $('.search-box form').attr('action','/search/');
  
  // box script
  if($('.box').length)
  {
    $('.box .close-btn').click(function(e)
    {
      $(this).parents('.box').hide(300);
    });
  }
  
  // main menu
  $('#main-nav a:contains("Shop"), ').each(function()
  {
    var str = $(this).html();
    $(this).html(str.replace('Shop','<span>Shop</span>'));
  });
  
  // breadcrumb
  $('#breadcrumb .item').eq($('#breadcrumb .item').length-2).find('a').attr('href')
  
  var breadcrumb_back = $('#breadcrumb .item').eq($('#breadcrumb .item').length-2).find('a').attr('href');
  var breadcrumb_back_t = $('#breadcrumb .item').eq($('#breadcrumb .item').length-2).find('a').text();
  var breadcrumb_store_last = $('#breadcrumb .item:last a').attr('href');
  
  if($('.shop-product-detail').length) $('#breadcrumb .back-btn').attr('href',breadcrumb_store_last);
  else $('#breadcrumb .back-btn').attr('href',breadcrumb_back);
  
  // breadcrumb - lookbook
  $('.lookbook-breadcrumb #breadcrumb .back-btn span').text('BACK TO '+breadcrumb_back_t);
  $('.lookbook-breadcrumb .item:last').addClass('active');
  
  // sub menu
  $('#sub-menu h1 a:contains(" ")').each(function()
  {
    //var str = $(this).html();
    //$(this).html(str.replace('SHOP','<span>SHOP</span>'));
    $(this).html($(this).html().replace(/^(w+)/,'<span>$1</span>'));
  });
  
  // sub template
  if($('#article-body').length)
  {
    if(!$('#article-body .img img').attr('src').length)
    {
      $('#article-body .img').remove();
    }
  }
  
  // store input & label script
  // label clickable & input id
  $('.store:not(.checkout) .field, .store:not(.checkout) .mailout').each(function()
  {
    var id = 'store_'+$('input, select',this).attr('name');
    $('label',this).attr('for',id);
    $('input:not([type=hidden]), select:not([type=hidden])',this).attr('id',id);
  });
  
  // required fields
  $('.field label:contains(*)').each(function()
  {
    var text = $(this).html().replace('*','<span class="asterisk">*</span>');
    $(this).html(text);
    $(this).addClass('required-label');
    $(this).parents('.field').find('input,select,textarea').addClass('required');
  });
  
  // store | default country to canada
  // store | default to canada
  if($('#store-registration:not(".store-account") select[name=country], #store-address-book select[name=country]').length)
  {
    $('.store select[name=country]').val('38');
    update_zone($('.store select[name=country]').parents('form').get(0));
  }
  
  if($('.store select[name=shipping_country]').length)
  {
    $('.store select[name=shipping_country]').val('38');
    update_shipping_zone($('.store select[name=shipping_country]').parents('form').get(0));
  }
  
  // store | update cart number
  $('#mini-cart').html('CART (<span>'+$('.cart-count-item').length + ' ITEMS</span>)');
  
  // store | product list paination
  if($('#store-pagination').length)
  {
    var prev = $('#store-pagination .active').prev('li.page').find('a');
    var next = $('#store-pagination .active').next('li.page').find('a');
    
    // prev
    if(prev.length) $('#store-pagination .prev').attr('href',prev.attr('href')).show();
    else      $('#store-pagination .prev').hide();
    
    // next
    if(next.length) $('#store-pagination .next').attr('href',next.attr('href')).show();
    else      $('#store-pagination .next').hide();
    
    if(!$('#store-pagination .page').length){
      // if null, hide
      $('#store-pagination').hide();
    }else{
      // append to breadcrumb
      $('#store-pagination').insertAfter('#breadcrumb > ul').show();
    }
  }
});

// ajax add to cart
function submitorder(theform)
{
  // validate
  if($('.Color select').val().toLowerCase().search(/please_select/g) == -1 && $('.Size select').val().toLowerCase().search(/please_select/g) == -1)
  {  
    $('#product-nav .add-to-cart').hide();
    $('#product-nav .preloader').show();
  
    var url = theform.attr("action");
    var formdata = theform.serialize();
    
    $.post(url,formdata,function(data)
    {    
            
      // Update cart on success
      $("#mini-cart").html('CART (<span>'+$(data).find('.cart-count-item').length + ' ITEMS</span>)');
      
      // Add To Cart Message
      var qty = $('#product-detail .quantity input').val();
      $('#add-to-cart-msg span').text(qty);
      $('#add-to-cart-msg').fadeIn(500);
     
            
      // Reset form value
      $('.Color select').val('0');
      $('.Size select').val('0');
      $('.quantity input').val('1');
      
      // remove preloader
      $('#product-nav .add-to-cart').show();
      $('#product-nav .preloader').hide();
    });
  }
}

// ajax add to cart
function add_to_cart(theform)
{
  //disable cache in IE
  $.ajaxSetup({ cache: false });
  
  var error = 0;
  
  if(theform.find('.attributes > div select').length)
  {
    // validation
    theform.find('.attributes > div select').each(function()
    {
      if($('option:first',this).val() == $('option:selected',this).val())
        error += 1;
    });
  }
  
  if(error == 0)
  {
    theform.find('.add-to-cart').hide();
    theform.find('.add-to-cart-msg').hide();
    theform.find('.preloader').show();
  
    var url = theform.attr("action");
    var formdata = theform.serialize();
    
    $.post(url,formdata,function(data)
    {  
      // Update cart on success
      $("#mini-cart").html('CART (<span>'+$(data).find('.cart-count-item').length + ' ITEMS</span>)');
      
      //Sold out
      if($(data).find(".soldout").text().length)
      {
        theform.find('.sold-out-msg').text($(data).find(".soldout").text());
        theform.find('.add-to-cart-msg').hide();
        theform.find('.sold-out-msg').fadeIn(500);
      }
      else
      {
        // Add To Cart Message
        var qty = theform.find('.quantity input').val();
        theform.find('.add-to-cart-msg span').text(qty);
        theform.find('.sold-out-msg').hide();
        theform.find('.add-to-cart-msg').fadeIn(500);
      }
      
      // remove preloader
      theform.find('.add-to-cart').show();
      theform.find('.preloader').hide();
    });
  }
  
}


// console log
function log(msg) {
  if (window.console) console.log(msg);
}


// get url variables
function getUrlVars()
{
  var vars = [], hash;
  var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
  for(var i = 0; i < hashes.length; i++)
  {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
  }
  return vars;
}





/* reverseOrder : jQuery order reverser plugin
 * Written by Corey H Maass for Arc90
 * (c) Arc90, Inc.
 * 
 * Licensed under:Creative Commons Attribution-Share Alike 3.0 http://creativecommons.org/licenses/by-sa/3.0/us/
 */

(function($){$.fn.reverseOrder=function(){return this.each(function(){$(this).prependTo($(this).parent())})}})(jQuery);




var formatDate = function (formatDate, formatString) {
  if(formatDate instanceof Date) {
    var months = new Array("JAN","FEB","MAR","APR","MAY","JUN","JUL","AUG","SEP","OCT","NOV","DEC");
    var yyyy = formatDate.getFullYear();
    var yy = yyyy.toString().substring(2);
    var m = formatDate.getMonth();
    var mm = m < 10 ? "0" + m : m;
    var mmm = months[m];
    var d = formatDate.getDate();
    var dd = d < 10 ? "0" + d : d;
    
    var h = formatDate.getHours();
    var hh = h < 10 ? "0" + h : h;
    var n = formatDate.getMinutes();
    var nn = n < 10 ? "0" + n : n;
    var s = formatDate.getSeconds();
    var ss = s < 10 ? "0" + s : s;

    formatString = formatString.replace(/yyyy/i, yyyy);
    formatString = formatString.replace(/yy/i, yy);
    formatString = formatString.replace(/mmm/i, mmm);
    formatString = formatString.replace(/mm/i, mm);
    formatString = formatString.replace(/m/i, m);
    formatString = formatString.replace(/dd/i, dd);
    formatString = formatString.replace(/d/i, d);
    formatString = formatString.replace(/hh/i, hh);
    formatString = formatString.replace(/h/i, h);
    formatString = formatString.replace(/nn/i, nn);
    formatString = formatString.replace(/n/i, n);
    formatString = formatString.replace(/ss/i, ss);
    formatString = formatString.replace(/s/i, s);

    return formatString;
  } else {
    return "";
  }
}


jQuery.extend({
  getUrlVars: function(){
    var vars = [], hash;
    var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
    for(var i = 0; i < hashes.length; i++)
    {
      hash = hashes[i].split('=');
      vars.push(hash[0]);
      vars[hash[0]] = hash[1];
    }
    return vars;
  },
  getUrlVar: function(name){
    return jQuery.getUrlVars()[name];
  }
});


$(document).ready(function()
{
  
/* CAROUSEL SCRIPTS */
if($(".the-carousel-gallery").length > 0)
{

  //Event handler for the thumbnails
  $('.the-carousel-gallery .item').hover(function(i){   
    $(this).find("h1").stop().animate({bottom:0}, 300);
  },function() {
    $(this).find("h1").stop().animate({bottom:-200}, 300);
  });  
      
  $('.the-carousel-gallery').each(function()
  {
    //Carousel
    var $_total = $(this).find('.item').length;
    var $_total2 = Math.ceil($_total / 5);
    var $slideshow_width = $('.the-carousel-gallery .navigation').width();
    var $_total_width = $_total2 * $slideshow_width;
    var $_first = $(this).find('.item:first');
    var $npos = 0;

     if($_total_width < $(this).find('.navigation').width())
     {
      $_total_width = $(this).find('.navigation').width();
     }
        
    $(this).find(".screen").css("width","20000em");        
        
     $(this).find('.prev').live('click',function(e)
     {
      e.preventDefault();
  
      $npos--;
      if($npos < 0) $npos = $_total2-1;
      $(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:$npos * -($slideshow_width+15)}, 500);
       
      $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
      $(this).parents('.the-carousel-gallery').find(".itemLI").eq($npos).addClass("active");
     });
        
     $(this).find('.next').live('click',function(e)
     {
      e.preventDefault();
      $npos++;
      if($npos >= $_total2) $npos = 0;
  
      $(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:$npos * -($slideshow_width+15)}, 500);
      $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
      $(this).parents('.the-carousel-gallery').find(".itemLI").eq($npos).addClass("active");
     });

          
    //Pagination
    for( i=$_total2; i > 0; i--)
    {
      $("<li class='itemLI' rel="+(i-1)+"><a>"+i+"</a></li>").insertAfter($(this).find(".prevLI"));  
    };  
  
     $(this).find(".itemLI:first").addClass("active");
  
     $(this).find(".itemLI").live('click',function() {

    var pos = $(this).attr("rel");
    
    $(this).parents('.the-carousel-gallery').find(".itemLI.active").removeClass("active");
    $(this).addClass("active");
    $(this).parents('.the-carousel-gallery').find('.screen').stop().animate({left:pos * -($slideshow_width+15)}, 500);
   });
  //end each()  
});  
 
  //Remove pagination if there's only one page
  $(".pagination").each(function()
  {
    if($(this).find(".itemLI").length ==1)
    {
      $(this).hide();
    }
  });
}

/* TABS SCRIPTS */
  
  if($(".tabs").length > 0) {

    //Manually sort tab order
    if($(".tab:contains('JUST IN')").length) {
        $(".tab:contains('JUST IN')").insertBefore(".tab:contains('BRANDS')");
        $(".tab:contains('STAFF PICKS')").insertBefore(".tab:contains('BRANDS')");        
    }
    
    $(".tabs").each(function() {   
    
    var tabtotal = $(this).find(".tab").length;

    //Add count to each tab item
    for( i=0; i < tabtotal; i++){    
      $(this).find(".tab").eq(i).attr("rel",i);        
      $(".tab-content").eq(i).attr("rel",i);  
    }  
    
       $(".tab-content:first,.tab:first").addClass("active");
         
       $(".tab").click(function() {
          var pos = $(this).attr("rel");
          var contentpos = $(".tab-content[rel='"+pos+"']");
         
          $(".tab,.tab-content").removeClass("active");
          contentpos.addClass("active");
          $(this).addClass("active");
       });
    });
    
  }  
  
//end .ready()
});

(function($){
     $.fn.extend({
          center: function () {
                return this.each(function() {
                        var top = ($(window).height() - $(this).outerHeight()) / 2;
                        var left = ($(window).width() - $(this).outerWidth()) / 2;
                        $(this).css({position:'absolute', margin:0, top: (top > 0 ? top : 0)+'px', left: (left > 0 ? left : 0)+'px'});
                });
        }
     });
})(jQuery);


var openPopup = window.open;

function show_msg(msg) { alert(msg); }

function validateForm() {
	missing_required = 0;

	for (i = 0; i < arguments.length; i++) {
		if(arguments[i] == '') {
			missing_required = 1;
		}
	}

	if(missing_required) {
		alert("A required form field is missing.");
		return false;
	} else {
		return true;
	}
}

function expCustomLink(myURL) {
	location.href = myURL;
}

function setUrl(path) {
	document.location.href = path;
}

function expArticleLink(sectionId, articleId) {
	location.href = '/index.php?section_id=' + sectionId + '&section_copy_id=' + articleId;
}

function expPopupWindow(url, widthVal, heightVal, resizableVal, scrollbarsVal, toolbarVal, locationVal, directoriesVal, statusVal, menubarVal, copyHistoryVal) {

	var attributes = "width="  	 	 + widthVal       +
				 	 ",height=" 	 + heightVal      +
				 	 ",resizable="  + resizableVal  +
				 	 ",scrollbars="  + scrollbarsVal  +
				 	 ",toolbar=" 	 + toolbarVal 	  +
				 	 ",location=" 	 + locationVal 	  +
				 	 ",directories=" + directoriesVal +
				 	 ",status=" 	 + statusVal 	  +
				 	 ",menubar=" 	 + menubarVal 	  +
				 	 ",copyhistory=" + copyHistoryVal;

	window.open(url, 'WindowName', attributes);
}

function xprLog(msg) {
    if (window.console) console.log(msg);
}

if (document.addEventListener) {  
    document.addEventListener("DOMContentLoaded", function () { if (typeof onXprPageLoad == 'function') onXprPageLoad(); }, false);
} else if (document.attachEvent) {  
    document.attachEvent('DOMContentLoaded', function () { if (typeof onXprPageLoad == 'function') onXprPageLoad(); });
}  

