var SelectedRadioButton = null;
var AjaxType = "";
var PossibleColorsAndSizes;
var QuickSelectTimeoutBag = new Array();
var chat;

//variables needed for power reviews
var productSTYLE = "";
var pr_merchant_group_id = 10282;
var pr_site_id = 1;
var pr_read_review = "";

$(function() {

$("#pretty1, #pretty2, #pretty3, #pretty4, #pretty5, #pretty6, #pretty7, #pretty8").tooltip({
	track: false,
	showURL: false,
	predelay: 500,
	fixPNG: true,
	showBody: " - ",
	offset: [175, 20]
	
	});

});

$(document).ready(function() {	
//	$("area[rel^='prettyPhoto3']").prettyPhoto3();	
	
	//set initial radiobutton states
	$("#RankingSortContainer input").attr("checked", false);	
			
	//set the on event behaviors of the controls
	BindBehaviors();
	
	//crawl the hidden html that contains the data about which color controls should be disabled 
	//when a given size control is selected, and vice versa, and create an array out of it
	BuildArrayOfPossibleColorsAndSizes();
		
	
});

function chatpop()
{
	WTonReady();
}

function isNonblank(s) { 
   var isNonblank_re    = /\S/; 
   return String (s).search (isNonblank_re) != -1 
}

function regIsEmail(fData) 
  { 
      var reg = new RegExp("^[0-9a-zA-Z\.]+@[0-9a-zA-Z]+[\.]{1}[0-9a-zA-Z]+[\.]?[0-9a-zA-Z]+$"); 
      return reg.test(fData); 
  }

function set_cookie(name, value)
{

var expdate = new Date (); // pre-set to the current time and date
expdate.setTime(expdate.getTime() + 1000 * 60 * 60 * 24 * 365); // add one year to it 
//365 days/year * 24 hours/day * 60 minutes/hour * 60 seconds/minute * 1000 milliseconds/second
// = howevermany milliseconds/year. So this adds one year, it'll expire in one year.

document.cookie = name + "=" + escape(value) + "; expires=" + expdate.toGMTString() + "; path=/";
}

function wopen(url, name, w, h)
{
// Fudge factors for window decoration space.
 // In my tests these work well on all platforms & browsers.
w += 32;
h += 96;
 var win = window.open(url,
  name,
  'width=' + w + ', height=' + h + ', ' +
  'location=yes, menubar=no, ' +
  'status=no, toolbar=no, scrollbars=yes, resizable=yes');
 win.resizeTo(w, h);
 win.focus();
}

testStatus = function () 
{
if (chat.status === "ready") 

{
	document.getElementById("ctch").style.display = "block";
	}
else
	{
	wopen('/en-us/customerservice/contactus/chatcontactus.aspx?a=|','popup',400,500);
	}
};

function WTonReady () {
chat = Wt.chat.PublicChat;
chat.init ({
statusCallback: testStatus,
startOptions: {
window: {
top: 100,
left: 100,
width: 475,
height: 600,
cssUrl: 'http://www.jockey.com/css/chat.css',
logoUrl: 'http://www.jockey.com/images/livehelp/HeadlineImage.jpg',
title: 'Chat with a Live Representative!'
}
}
});
}

function WTfname()
{
return document.Form1.wt_first.value;
}

function WTlname()
{
return document.Form1.wt_last.value;
}

function WTemail()
{
return document.Form1.wt_email.value;
}

function WTinittest()
{
return document.Form1.init_text.value;
}

function WTservername()
{
return document.Form1.wt_servername.value;
}

btnChatNow_onClick = function () 
{
document.getElementById("emlb").style.display = "none";
document.getElementById("msgb").style.display = "none";

if (isNonblank(document.Form1.wt_email.value))
{
	if (!regIsEmail(document.Form1.wt_email.value))
	{
	document.getElementById("emlb").style.display = "block";
	return;
	}
}

if (!isNonblank(document.Form1.init_text.value))
{
document.getElementById("msgb").style.display = "block";
return;
}

if (document.Form1.wt_first.value == '')
 set_cookie ( "WTFirst", "null");
else	
 set_cookie ( "WTFirst", document.Form1.wt_first.value);
if (document.Form1.wt_last.value == '')
 set_cookie ( "WTLast", "null");
else 
 set_cookie ( "WTLast", document.Form1.wt_last.value);
if (document.Form1.wt_email.value == '')
 set_cookie ( "WTEmail", "null");
else
 set_cookie ( "WTEmail", document.Form1.wt_email.value);
 
 set_cookie ( "WTtxt", document.Form1.init_text.value);
 	chat.start({
    	initialText: 'message',
        info: {
            'Name_First': WTfname(),
            'Name_Last': WTlname(),
            'email': WTemail(),
            'message' : WTinittest(),
            'server' : WTservername()
        }
    });
 document.getElementById("ctch").style.display = "none";
}

function BindBehaviors()
{		
	$("#SizeSortButtonContainer > div").click(function() {
		if (!$(this).hasClass("Disabled"))
		{
			if ($(this).hasClass("Selected"))
			{ $(this).removeClass("Selected"); }
			else
			{
				$("#SizeSortButtonContainer > div").removeClass("Selected");
				$(this).addClass("Selected");
			}		
			DisableControls();		
			SortAndFilterStyles();
		}
	});	
	
	$("#ColorSortButtonContainer > div").click(function() {
		if (!$(this).hasClass("Disabled"))
		{
			if ($(this).hasClass("Selected"))
			{ $(this).removeClass("Selected"); }
			else
			{
				$("#ColorSortButtonContainer > div").removeClass("Selected");
				$(this).addClass("Selected");
			}				
			DisableControls();		
			SortAndFilterStyles();
		}
	});	


	$("#allcolordisplay").click(function() {
		$("#ColorSortButtonContainer > div").removeClass("Selected");
		DisableControls();		
		SortAndFilterStyles();
	});

	$("#allsizedisplay").click(function() {
		$("#SizeSortButtonContainer > div").removeClass("Selected");
		DisableControls();		
		SortAndFilterStyles();
	});
	
	//configure the QuickSelect
	var ModalWidth = $.browser.msie ? 660 : 650;	
	$("#dialog").QuickSelect({
		autoOpen: false,
		bgiframe: true,
		resizable: false,
		minHeight:400,
		width:ModalWidth,
		modal: true,
		overlay: {
			backgroundColor: '#000',
			opacity: 0.5
		}
	});		
}

function BuildArrayOfPossibleColorsAndSizes()
{
	PossibleColorsAndSizes = { "ColorList" : new Array(), "SizeList" : new Array() };
	
	var PossibleColorsForSize = $("#divSizes > div");
	for (var i = 0; i < PossibleColorsForSize.size(); i++)
	{
		 var ColorList = PossibleColorsForSize[i].innerHTML.split(",");
		 var ColorBag = new Array();
		 for (var k = 0; k < ColorList.length; k++)
		 {
			ColorBag[ColorList[k].toUpperCase()] = true;
		 }
		 PossibleColorsAndSizes.ColorList[PossibleColorsForSize[i].id.toUpperCase()] = ColorBag;
	}
	
	var PossibleSizesForColor = $("#divColors > div");
	for (var j = 0; j < PossibleSizesForColor.size(); j++)
	{
		var SizeList = PossibleSizesForColor[j].innerHTML.split(",");
		var SizeBag = new Array();
		for (var l = 0; l < SizeList.length; l++)
		{
			SizeBag[SizeList[l].toUpperCase()] = true;
		}
		PossibleColorsAndSizes.SizeList[PossibleSizesForColor[j].id.toUpperCase()] = SizeBag;
	}
}

function ProductLinkMouseOver(LinkIndex, Link)
{	
	var ProductId = Link.rel;
	$(".QuickSelectButton[rel!=" + ProductId + "]").css("display", "none");
	var TimeoutId = setTimeout(function(){		
		//show the quickview button	
		$(".QuickSelectButton[rel='" + ProductId + "']").css("display", "block");
	}, 1);
	QuickSelectTimeoutBag[ProductId + "inLink"] = { 'ProductId' : ProductId, 'TimeoutId' : TimeoutId };
}

function ProductLinkMouseOut(ProductId)
{
	var TimeoutId = setTimeout(function(){		
		//hide the quickview button
		$(".QuickSelectButton[rel='" + ProductId + "']").css("display", "none");
	}, 1);
	QuickSelectTimeoutBag[ProductId + "outLink"] = { 'ProductId' : ProductId, 'TimeoutId' : TimeoutId };
}

function QuickSelectButtonMouseOver(QuickSelectButton)
{
	var ProductId = QuickSelectButton.rel;
	clearQuickSelectTimeouts([ProductId + "outLink"]);	
	$("#" + QuickSelectButton.id).addClass("QuickSelectButtonMouseOver");
}

function QuickSelectButtonMouseOut(QuickSelectButton)
{
	var ProductId = QuickSelectButton.rel;
	clearQuickSelectTimeouts([ProductId + "inLink"]);	
	$("#" + QuickSelectButton.id).removeClass("QuickSelectButtonMouseOver");
}

function SwatchMouseOver(Swatch)
{	
	var SwatchId = $(Swatch).attr("rel");
	var ProductId = $(Swatch).parent().attr("rel");
	
	$("#pnlRepeaterContainer .SwatchOverlay[rel=" + ProductId + "]").css("display", "block");
	$("#pnlRepeaterContainer .SwatchOverlay[rel=" + ProductId + "] img").attr("src", "/Swatches/" + SwatchId + "_l.jpg");
	
}

function SwatchMouseOut()
{
	$("#pnlRepeaterContainer .SwatchOverlay").css("display", "none");
}

function SortAndFilterStyles()
{	
	var ControlStateObject = GetSortControlsState();
	var ProductsWrapper = $("#ProductsWrapper");
		var silmainbox = $("#silmainbox");
		silmainbox.html("<div style='text-align:center;width:100%;position:relative;top:80px;height:200px;'><img src='../../Images/loading.gif' /><br /><span class='LoadingText'>Loading...</span></div>");
	//ProductsWrapper.html("<div style='text-align:center;width:100%;position:relative;top:80px;height:200px;'><img src='../../Images/loading.gif' /><br /><span class='LoadingText'>Loading...</span></div>");
	ProductsWrapper.load(location.href + "&CallbackType=AjaxSort", ControlStateObject, function(){
		AjaxType = "Sort"; 				
	});		
	
	//var ControlStateObject = GetSortControlsState();
	//	var silmainbox = $("#silmainbox");
		//silmainbox.html("<div style='text-align:center;width:100%;position:relative;top:80px;height:200px;'><img src='../../Images/loading.gif' /><br /><span class='LoadingText'>Loading...</span></div>");
	
	//this should probably get refactored to $.ajax call so we can do error checking...
		//silmainbox.load(location.href + "&CallbackType=AjaxSort", ControlStateObject, function(){
			//AjaxType = "Sort"; 				
		//});	
}


function GetSortControlsState()
{
	var selectedSize = "";
	var selectedColor = "";
	var SortType = "";
	var selectedPage = "";

	//get selected size
	selectedSize = $("#SizeSortButtonContainer .Selected").attr("name") == null ? "" : $("#SizeSortButtonContainer .Selected").attr("name");
	
	
	//get selected color
	selectedColor = $("#ColorSortButtonContainer .Selected").attr("name") == null ? "" : $("#ColorSortButtonContainer .Selected").attr("name");
	
	
	//get selected page
	selectedPage = $("#TopPageButtonContainer .Selected").attr("name") == null ? "" : $("#TopPageButtonContainer .Selected").attr("name");
	if(selectedPage == "")
	{
		selectedPage = $("#BottomPageButtonContainer .Selected").attr("name") == null ? "" : $("#BottomPageButtonContainer .Selected").attr("name");
	}
			
	//get sort type	
	switch ($("#RankingSortContainer > .sorthighlight").attr("id"))
	{
		case "SortLowToHigh":
			SortType = "PriceAscending";
			break;
		case "SortHighToLow":
			SortType = "PriceDescending";
			break;
		case "SortTopRated":
			SortType = "Rating";
			break;
		case "SortNewest":
			SortType = "New";
			break;
		default:
			SortType = "";
			break;
	}
	
	var ControlStateData = {"SortType": SortType, "SelectedSize" : selectedSize, "SelectedColor" : selectedColor, "SelectedPage" : selectedPage};
	
	return ControlStateData;
}

function DisableControls()
{		
	var SelectedSizeControlID = $("#SizeSortButtonContainer > .Selected").attr("id");
	var SelectedSize = $("#SizeSortButtonContainer > .Selected").attr("name");
	var SelectedColorControlID = $("#ColorSortButtonContainer > .Selected").attr("id");
	var SelectedColor = $("#ColorSortButtonContainer > .Selected").attr("name");
	var selectedPage = "";
	//get selected page
	selectedPage = $("#TopPageButtonContainer .Selected").attr("name") == null ? "" : $("#TopPageButtonContainer .Selected").attr("name");
	if(selectedPage == "")
	{
		selectedPage = $("#BottomPageButtonContainer .Selected").attr("name") == null ? "" : $("#BottomPageButtonContainer .Selected").attr("name");
	}
			
	
	if($("#SizeSortButtonContainer > .Selected").length == 0) //only disable color controls when there is a size refinement selected
	{
		$("#ColorSortButtonContainer > .Disabled").html("");
		$("#ColorSortButtonContainer > .Disabled").removeClass("Disabled");
	}
	else
	{				
		//for each color control, enable or disable based if that color is available in the selected size 
		$("#ColorSortButtonContainer > div").each(
			function(){				
				if (PossibleColorsAndSizes.ColorList[SelectedSize.toString()] != null && PossibleColorsAndSizes.ColorList[SelectedSize.toString()][$(this).attr("name").toUpperCase()] == true)
					{
					$(this).removeClass("Disabled");
					$(this).html("");
					}
				else
				{
					$(this).addClass("Disabled");
					$(this).html("<div class='colorTransparency'></div><div class='colorNA'>N/A</div>");
				}
			});
	}	
	
	if($("#ColorSortButtonContainer > .Selected").length == 0) //only disable size controls when there is a color refinement selected
	{
		$("#SizeSortButtonContainer > .Disabled").removeClass("Disabled");
	}
	else
	{
		//for each size checkbox, enable or disable based on if their innerHTML is in the sizemap
		$("#SizeSortButtonContainer > div").each(
			function(){
				if (PossibleColorsAndSizes.SizeList[SelectedColor.toUpperCase()] != null && PossibleColorsAndSizes.SizeList[SelectedColor.toUpperCase()][$(this).attr("name").toUpperCase()] == true)
					$(this).removeClass("Disabled");
				else
					$(this).addClass("Disabled");		
			});
	}
}


function clearQuickSelectTimeouts(TimeoutBagKeys)
{
	if(TimeoutBagKeys == null) //if no TimeoutId is specified, clear all timeouts.
	{
		for (var i = 0; i < TimeoutBag.length; i++)
		{
			clearTimeout(QuickSelectTimeoutBag[i].TimeoutId);
		}
	}
	else //otherwise, an array of keys for the timeout bag has been passed in. clear those timeouts.
	{
		for (var i = 0; i < TimeoutBagKeys.length; i++)
		{
			if (QuickSelectTimeoutBag[TimeoutBagKeys[i]] != null)
			{
				clearTimeout(QuickSelectTimeoutBag[TimeoutBagKeys[i]].TimeoutId);
			}
		}		
	}
}

function RemoveSortHighlight()
{
	$("#SortTopRated").removeClass("sorthighlight");
	$("#SortNewest").removeClass("sorthighlight");
	$("#SortHighToLow").removeClass("sorthighlight");
	$("#SortLowToHigh").removeClass("sorthighlight");
}

function SortClick(element)
{


		$("#RankingSortContainer > span").removeClass("sorthighlight");
		$(element).addClass("sorthighlight");
	
		DisableControls();		
		SortAndFilterStyles();
	
}

function TopPageClick(element)
{
	//$("#TopPageButtonContainer > div").click(function(){
		if (!$(element).hasClass("Disabled"))
		{
			recordPagingLink('Paging Links', $(element).text());	
			if ($(element).hasClass("Selected"))
			{ $(element).removeClass("Selected"); }
			else
			{
				$("#TopPageButtonContainer > div").removeClass("Selected");
				$("#BottomPageButtonContainer > div").removeClass("Selected");
				$(element).addClass("Selected");
			}		
			DisableControls();		
			SortAndFilterStyles();
		}
	//});
}

function BottomPageClick(element)
{
	//$("#BottomPageButtonContainer > div").click(function(){
		if (!$(element).hasClass("Disabled"))
		{
			if ($(element).hasClass("Selected"))
			{ $(element).removeClass("Selected"); }
			else
			{
				$("#BottomPageButtonContainer > div").removeClass("Selected");
				$("#TopPageButtonContainer > div").removeClass("Selected");
				$(element).addClass("Selected");
			}		
			DisableControls();		
			SortAndFilterStyles();
		}
	//});
}

