﻿var ie = (/MSIE/.test(navigator.userAgent)), deprecated = (/MSIE ((5\.5)|6)/.test(navigator.userAgent) && navigator.platform == "Win32"), cH = 0, dH = 0;

//Abhishek: fix for collaboration/blog not loading the complete content
$(window).load(function () {
	if (flagNoConfigContent) {
		configContent();
	}
});

$(document).ready(function () {
	if (deprecated) {
		pngFix();
		bgFix();
	}
	configSearch();
	configPersistentCart();
	configMenus();
	if ($('.mybag').length)
		loadMiniCart();
	configEmailSignUp();
	configAllInputs();

	if ($('#footer').length)
		initFooter(); //temp main footer link on and off call

	if ($('.neutra').length)
		fontReplace();
	if ($('#checkoutheader span').length)
		fontReplace();
	if ($('#productslist').length) {
		configFilter();
		initProductsList();
	}
	if ($('#homepage').length)
		initHomePage();
	if ($('#fitguide').length)
		initFitGuide();
	if ($('#aboutUsPage').length)
		initAboutUsPage();
	if ($('#helpCustomerCare').length)
		initHelpPage();
	if ($('#storeLocator').length)
		initStoreLocator();
	if ($('#productDetailsPage').length) {
		initDetailsPage();
	}
	if ($('#menPage').length)
		initMenPage();
	if ($('#womenPage').length)
		initWomenPage();
	if ($('select.ddl').length)
		applyCusel();
	if ($('#shoppingBag').length)
		configShoppingBag();
	if ($('#language').length) {
		loadMessages();
	}
	if ($('#collaborations').length) {
		initCollaborations();
		$('#scrollcontainer').jScrollPane();

	}
	if ($('#mailingListPage').length) {
		intiMaillingList();
	}
	if ($('#giftCertPage').length) {
		initGiftCard();
	}
//	if ($('#ckane').length) {
//		initCKane();
//	}

	if ($('#tickerPop').length) {
		initTickerPopup();

}



});

moveTicker = function () {
	$('.ticker a').animate({
		left: 350
	}, {
		duration: 25000,
		specialEasing: {
		  width: 'linear'
		},
		complete: function () {
			$('.ticker a').css({ 'left': -350 });
			moveTicker();
		}
	});
}

//FEATURE BANNER click event
//initFeatureBanner = function () {
//	$('.featureBanner').click(function () {
//		if ($('.featureBanner_notes').css('display') == 'none') {
//			$('.featureBanner_notes').css({ 'display': 'block' });
//		}
//		else {
//			$('.featureBanner_notes').css({ 'display': 'none' });
//		}
//	});
//	$('.featureBanner_notes').click(function () {
//		$(this).css({ 'display': 'none' });
//	});
//}

$(window).resize(function () {
	if (flagNoConfigContent) {
		configContent();
	}
	if ($('#productslist').length)
		productsListResized();
	if ($('#productDetailsPage').length) {
		outOfStockWindowResize();
		if ($('.fullZoomOverlay').css('display') == 'block' || $('#quickView').css('display') == 'block' || $('#showNotes').css('display') == 'block') {
			configureModal();
		}
	}
	//positionEmail();
});

applyCusel = function () {
  $.getScript('/store/os/js/jquery.cusel.js', function () {
    $.getScript('/store/os/js/jquery.cusel.scrollpane.js');
    $.getScript('/store/os/js/jquery.mousewheel.js');
    var params = {
      changedEl: "select.ddl",
      visRows: 8,
      checkZIndex: true
    }
    cuSel(params);
  });
}

pngFix = function () {
	$.getScript('/layout/js/png-fix.js', function () {
		//common elements
		PNG.fix('#container, h1, #header, #header input, #header ul ul, #footer, #footer input, #footer ul.social a, .bg00040');
		//page specific elements
		if ($('.navigation').length)
			PNG.fix('.navigation');
		if ($('.shadow').length) {
			PNG.fix('.top, .bottom, .sides');
		}
		if ($('.filter').length)
			PNG.fix('.filter div');
		if ($('#homepage .stylenotes').length) {
			PNG.fix('.stylenotes, .stylenotes img');
		}
		if ($('#productDetailsPage').length) {
			PNG.fix('.bgimage,.bgthumb,.icons img,.moreToLove,.icosn,.recentlyViewed,.hoverMask');
		}
		if ($('#aboutUsPage').length) {
			PNG.fix('img');
		}
		if ($('#productsListPage').length) {
			PNG.fix('.hoverMask, .quickView, .icosn, #JWorldLoader1');
		}
	});
}

bgFix = function (dH) {
  $('#background').hide();
}

configInfoBar = function () {
  collectionOfInfoBarHeights = new Array();
  collectionOfProductOffets = new Array();

  $('.infobar').each(function (index) {
    var productTopOffset = $(this).parents('.product').offset().top;
    var infoBarHeights = parseInt($(this).outerHeight());

    collectionOfInfoBarHeights[index] = infoBarHeights;
    collectionOfProductOffets[index] = productTopOffset;
  });

  $(collectionOfInfoBarHeights).each(function (index) { //looping through the array of OUTER HEIGHTs on the info bars
    if (collectionOfInfoBarHeights[index] > 41) { //as the index increments, this is checking to see if the value returned by each loop is greater than 41. If it is... [index] being appended to the array name gives us the value key paired to that index during each loop through. 
      $(collectionOfProductOffets).each(function (offsetIndex) { //if an infobar height from the collectionOfInfoBarHeights is greater than 41, we want to loop through the array of '.product. container OFFSETS are.
        if (collectionOfProductOffets[offsetIndex] == collectionOfProductOffets[index]) { //as we loop through, check the indexes of both arrays to find a match.
          $('.infobar:eq(' + offsetIndex + ')').height(collectionOfInfoBarHeights[index]); //if a match is found, set the height of the product containers on the same row as the infbar with a varied height
        }
      });
    }
  });
}

configPersistentCart = function (ul) {
  $('ul.global li.mybag').hover(function () {
    ul = $(this).children('ul');
    ul.showContent('slow');
    clearTimeout(timeOut);
  }, function () {
    ul = $(this).children('ul');
    ul.hideContent('fast');
  });
}
var timeOut;
openCloseMiniCart = function () {
	$(window).scrollTop(0);
	$.ajax({
		url: '/store/minicart.aspx',
		cache: false,
		success: function (html) {
			$('.mybag ul').html(html).showContent('slow', function () {
				timeOut = setTimeout(function () { $('.mybag ul').hideContent('fast'); }, 20000);
			});
		}
	});
	render_cart_header("CartItemsLBGet", "CartTotalLBGet");
	clickAnywhereCloseCart();
}

clickAnywhereCloseCart = function () {
	$('#content,#background').click(function () {
		$('.mybag ul').hideContent('fast');
	});
}

loadMiniCart = function () {
  $.ajax({
  	url: '/store/minicart.aspx',
  	cache: false,
    success: function (html) {
      //alert(html);
      $('.mybag ul').html(html);
    }
  });
  render_cart_header("CartItemsLBGet", "CartTotalLBGet");
}

removeItem = function (rid) {
  $.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    url: '/store/minicart.aspx/RemoveItem',
    data: '{rid:"' + rid + '"}',
    dataType: 'json',
    success: function (msg) {
      loadMiniCart();
    },
    error: function (e) { alert('error: ' + e.responseText); }
  });
}

configMenus = function (ul) {
  $('ul.main li.menu').hover(function () {
    ul = $(this).children('ul');
    ul.css({ left: $(this).position().left });
    $(this).addClass('on');
    ul.showContent('slow');
  }, function () {
    $(this).removeClass('on');
    ul = $(this).children('ul');
    ul.hideContent('fast');
  });
}

configContent = function (wH, hH, nH, fH, h) {
	if (!$('#homepage').length) {
		wH = $(window).height(), hH = $('#header').height(), cH = cH == 0 ? $('#content').height() : cH, nH = $('#content').height(), fH = $('#footer').height(), dH = dH == 0 ? hH + cH + fH : dH;
		h = wH > dH ? ((wH - 1) - (hH + fH)) : cH;
		$('#content').height(h);
		if ($('.navigation').length) $('.navigation').height(h);
	}
}


reconfigContent = function () {
	$('#content').height('auto'); cH = 0;
	if (flagNoConfigContent) {
		configContent();
	}
}

////////////////////// Flag to disable configContent() \\\\\\\\\\\\\\\\\\\\\\\\
 var flagNoConfigContent = $('.blog_indentifier').length || $('#collab-ac').length ? false : true;

 configSearch = function () {
 	$('#searchcontent').focus(function () {
 		if ($(this).attr('value') == $(this).attr('title')) $(this).attr('value', '');
 	}).blur(function () {
 		if ($(this).attr('value') == '') $(this).attr('value', $(this).attr('title'));
 	}).keydown(function (event) {
 		if (event.keyCode == 13) {
 			MM_goToURL('parent', 'http://jbrand.jbrandjeans.com/search?w=' + $('#searchcontent').val());
 			return document.MM_returnValue;
 		}
 	});
 	$('#Submit1').click(function () {
 		MM_goToURL('parent', 'http://jbrand.jbrandjeans.com/search?w=' + $('#searchcontent').val());
 		return document.MM_returnValue;
 	});
 }

configEmailSignUp = function () {
  $('#minimailinglist').focus(function () {
    if ($(this).attr('value') == $(this).attr('title')) $(this).attr('value', '');
  }).blur(function () {
    if ($(this).attr('value') == '') $(this).attr('value', $(this).attr('title'));
  }).keydown(function (event) {
    if (event.keyCode == 13) {
      MM_goToURL('parent', '/store/mailinglist.aspx?EM=' + $('#minimailinglist').val());
      return document.MM_returnValue;
    }
  });
  $('#mailinglistbutton').click(function () {
    MM_goToURL('parent', '/store/mailinglist.aspx?EM=' + $('#minimailinglist').val());
    return document.MM_returnValue;
  });
}

configAllInputs = function () { ///THIS FUNCTION USES A CLASS TO HANDLE ALL OF THE INPUT BOXES THAT NEED TO HAVE DEFAULT TEXT THAT DISAPPEARS ONFOCUS
  $('.allInputs').focus(function () {
    if ($(this).attr('value') == $(this).attr('title')) $(this).attr('value', '');
  }).blur(function () {
    if ($(this).attr('value') == '') $(this).attr('value', $(this).attr('title'));
  });
}

configureModal = function () {
  var height = $(document).height(); var width = $(window).width();
  $("#bgModal").css({ 'height': height, 'width': width, 'position': 'absolute' }).show();
}

fontReplace = function () {
  Cufon.replace('.neutra');
  $('.neutra').show();
}

loadQuickLook = function (id, placementMemberId) {
    var url = '/store/QuickLook.aspx?productid=' + id + '&action=1';
    if (placementMemberId) {
        url += '&placementMemberID=' + placementMemberId;
    }
    $.ajax({
        url: url,
        success: function (html) {
            $('div#quickView').html(html).show();
            $('div#bgModal').show();
            configureModal();
            positionQuickLook();
            BuildQuicklookJs();
            change_unitcost(id);
            initializeAllProducts('true');
            fontReplace();
            $('.closeModal').click(function () {
                $('div#quickView').hide();
                if ($('.fullZoomOverlay').css('display') == 'block') {
                    return false;
                }
                else {
                    $('div#bgModal').hide();
                }
            });
            $('#bgModal').click(function () { $('div#quickView,div#bgModal,').hide(); });
            clearTimeout(timer);
        },
        error: function (e) {
            alert(e.responseText);
        }
    });
}

positionQuickLook = function () {
  var windowHeightCenterAxis = Math.floor($(window).height() / 2);
  var popupCenterAxis = Math.floor($('#quickView .top').outerHeight() / 2);
  var offSetFromTop = $('#header').outerHeight();
  var popupTopPadding = (parseInt($('#quickView .top').css('padding-top')) + offSetFromTop) * -1; //wrapping the parse in a parenthesis forces the addition to fire before the multiplication
  var scrollPosition = $(window).scrollTop();
  var popupTopValue = windowHeightCenterAxis - popupCenterAxis - offSetFromTop;
  popupTopValue = (popupTopValue >= popupTopPadding) ? popupTopValue : popupTopPadding;
  $("#quickView .top").css({ 'top': popupTopValue + scrollPosition }).show();

  applyCusel();
}

positionOutOfStockPop = function () {
  var windowHeightCenterAxis = Math.floor($(window).height() / 2);
  var popupCenterAxis = Math.floor($('.stockPopContain').outerHeight() / 2);
  var offSetFromTop = $('#header').outerHeight();
  var popupTopPadding = (parseInt($('.stockPopContain').css('padding-top')) + offSetFromTop) * -1; //wrapping the parse in a parenthesis forces the addition to fire before the multiplication
  var scrollPosition = $(window).scrollTop();
  var popupTopValue = windowHeightCenterAxis - popupCenterAxis - offSetFromTop;

  popupTopValue = (popupTopValue >= popupTopPadding) ? popupTopValue : popupTopPadding;
  $(".stockPopContain").css({ 'top': popupTopValue + scrollPosition }).show();
}

$.fn.showContent = function (s, cb) {
  ie ? $(this).stop(true, true).show(0, cb) : $(this).stop(true, true).fadeIn(s, cb);
}

$.fn.hideContent = function (s) {
  ie ? $(this).stop(true, true).hide() : $(this).stop(true, true).fadeOut(s);
}

loadMessages = function (l, p) {
  l = $('#language').val(); p = '/layout/js/messages.#.js';
  $.getScript(p.replace('#', l));
}

 loadStyleNotes = function () {
 	$('.closeNotes, #bgModal').click(function () { $('div#showNotes,div#bgModal').hide(); $('div#showNotes').empty(); });

//==========SCRIPTS TO ENABLE STYLE NOTES SLIDES===========
//  var totalLength = $("#filterSlides div").length;
//  $("#filterSlides div:first").addClass('current');
//  $('.btnPrevious').addClass('off');
//  $('.btnNext img:first').click(function () {
//    $('.btnPrevious').removeClass('off');
//    if ($('#filterSlides .current').index() < totalLength - 1) {
//      $('.current').removeClass('current').next('div').addClass('current').css({ 'left': '400px' }).animate({
//        left: 0
//      }, 800, function () {
//        if ($('#filterSlides .current').index() == totalLength - 1) {
//          $('.btnNext').addClass('off');
//        }
//      });
//    }
//    else {
//      return false;
//    }
//  });
//  $('.btnPrevious img:first').click(function () {
//    $('.btnNext').removeClass('off');
//    if ($('#filterSlides .current').index() > 0) {
//      $('.current').removeClass('current').prev('div').addClass('current').css({ 'left': '-400px' }).animate({
//        left: 0
//      }, 800, function () {
//        if ($('#filterSlides .current').index() == 0) {
//          $('.btnPrevious').addClass('off');
//        }
//      });
//    }
//    else {
//      return false;
//    }
//  });
//=========END SLIDES SCRIPTS============
}

showStyleNotes = function () {
  $('div#showNotes').load('/store/StyleNotesModalContent.aspx', { pid: $(this).attr('id').replace('jsn', '') }, function () { loadStyleNotes(); positionStyleNotes(); }); $('div#showNotes,div#bgModal').show(); configureModal();
}

submitReferAFriendForm = function (pid, pdp, from, to, confirm, message, optIn, url) {
  from = $('#emailaddress');
  to = $('#recipientemail');
  confirm = $('#confirmemail');
  message = $('#messagearea');
  optIn = $('input[name$="signup"]').is(':checked');
  url = window.location.href;
  var msg = $('.message'); var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; var defaultMessage = message.val() == message.attr('title');
  if (from.val() == from.attr('title')) {
    msg.text(messages.productDetails.referAFriend.enterYourEmail).show();
    return false;
  }
  else if (!regex.test(from.val())) {
    msg.text(messages.productDetails.referAFriend.enterValidYourEmail).show();
    return false;
  }
  if (to.val() == to.attr('title')) {
    msg.text(messages.productDetails.referAFriend.enterRecipientEmail).show();
    return false;
  }
  else if (!regex.test(to.val())) {
    msg.text(messages.productDetails.referAFriend.enterValidRecipientEmail).show();
    return false;
  }
  else if (confirm.val() != to.val()) {
    msg.text(messages.productDetails.referAFriend.emailMismatch).show();
    return false;
  }
  $.ajax({
    type: pdp ? 'POST' : 'GET',
    contentType: 'application/json; charset=utf-8',
    url: pdp ? '/store/ProductDetails.aspx/SubmitReferAFriendForm' : '/Service.svc/SubmitReferAFriendForm',
    data: pdp ? '{from:"' + from.val() + '",to:"' + to.val() + '",subject:"' + messages.productDetails.referAFriend.subject + '",message:"' + (defaultMessage ? messages.productDetails.referAFriend.defaultMessage : message.val()) + '",defaultMessage:' + defaultMessage + ',optIn:' + optIn + ',pid:' + pid + '}' : { from: from.val(), to: to.val(), subject: messages.productDetails.referAFriend.subject, message: (defaultMessage ? messages.productDetails.referAFriend.defaultMessage : message.val()), defaultMessage: defaultMessage, url: url, optIn: optIn },
    dataType: 'json',
    success: function () {
      msg.text(messages.productDetails.referAFriend.thankYou).show();
    },
    error: function (e) { msg.text(messages.productDetails.referAFriend.error).show(); }
  });
  }

  submitZoomReferAFriendForm = function (pid, from, to, confirm, message, optIn, url) {
  	from = $('#emailaddress-zoom');
  	to = $('#recipientemail-zoom');
  	confirm = $('#confirmemail-zoom');
  	message = $('#messagearea-zoom');
  	optIn = $('input[name$="signup-zoom"]').is(':checked');
  	url = window.location.href;
  	var msg = $('.message-zoom'); var regex = /^\w+([\.-]?\w+)*@\w+([\.-]?\w+)*(\.\w{2,3})+$/; var defaultMessage = message.val() == message.attr('title');
  	if (from.val() == from.attr('title')) {
  		msg.text(messages.productDetails.referAFriend.enterYourEmail).show();
  		return false;
  	}
  	else if (!regex.test(from.val())) {
  		msg.text(messages.productDetails.referAFriend.enterValidYourEmail).show();
  		return false;
  	}
  	if (to.val() == to.attr('title')) {
  		msg.text(messages.productDetails.referAFriend.enterRecipientEmail).show();
  		return false;
  	}
  	else if (!regex.test(to.val())) {
  		msg.text(messages.productDetails.referAFriend.enterValidRecipientEmail).show();
  		return false;
  	}
  	else if (confirm.val() != to.val()) {
  		msg.text(messages.productDetails.referAFriend.emailMismatch).show();
  		return false;
  	}
  	$.ajax({
  		type: 'POST',
  		contentType: 'application/json; charset=utf-8',
  		url: '/store/ProductDetails.aspx/submitReferAFriendForm',
  		data: '{from:"' + from.val() + '",to:"' + to.val() + '",subject:"' + messages.productDetails.referAFriend.subject + '",message:"' + (defaultMessage ? messages.productDetails.referAFriend.defaultMessage : message.val()) + '",defaultMessage:' + defaultMessage + ',optIn:' + optIn + ',pid:' + pid + '}',
  		dataType: 'json',
  		success: function () {
  			msg.text(messages.productDetails.referAFriend.thankYou).show();
  		},
  		error: function (e) { msg.text(messages.productDetails.referAFriend.error).show(); }
  	});
  }

  positionStyleNotes = function () {
  	var windowHeightCenterAxis = Math.floor($(window).height() / 2);
  	var popupCenterAxis = Math.floor($('.snContents').outerHeight() / 2);
  	var offSetFromTop = $('#header').outerHeight();
  	var popupTopPadding = (parseInt($('.snContents').css('padding-top')) + offSetFromTop) * -1; //wrapping the parse in a parenthesis forces the addition to fire before the multiplication
  	var scrollPosition = $(window).scrollTop();
  	var popupTopValue = windowHeightCenterAxis - popupCenterAxis - offSetFromTop;

  	//popupTopValue = (popupTopValue >= popupTopPadding) ? popupTopValue : popupTopPadding;
  	$(".styleNotes").css({ 'top': popupTopValue + scrollPosition }).show();
}

function clearFilter(catid) {
    var base = "/store/productslist.aspx";
    window.location.href = base+"?categoryid=" + catid;
}


jQuery.fn.liScroll = function(settings) {
		settings = jQuery.extend({
		travelocity: 0.07
		}, settings);		
		return this.each(function(){
				var $strip = jQuery(this);
				$strip.addClass("newsticker")
				var stripWidth = 1;
				$strip.find("li").each(function(i){
				stripWidth += jQuery(this, i).outerWidth(true); 
				});
				var $mask = $strip.wrap("<div class='mask'></div>");
				var $tickercontainer = $strip.parent().wrap("<div class='tickercontainer'></div>");								
				var containerWidth = $strip.parent().parent().width();		
				$strip.width(stripWidth);			
				var totalTravel = stripWidth+containerWidth;
				var defTiming = totalTravel/settings.travelocity;	
				function scrollnews(spazio, tempo){
				$strip.animate({left: '-='+ spazio}, tempo, "linear", function(){$strip.css("left", containerWidth); scrollnews(totalTravel, defTiming);});
				}
				scrollnews(totalTravel, defTiming);				
				$strip.hover(function(){
				//jQuery(this).stop(); //stops scrolling on hovering over text
				},
				function(){
				var offset = jQuery(this).offset();
				var residualSpace = offset.left + stripWidth;
				var residualTime = residualSpace/settings.travelocity;
				scrollnews(residualSpace, residualTime);
				});			
		});	
};
