var SelectedRadioButton = null;
var AjaxType = "Sort";
var QuickSelectTimeoutBag = new Array();
var chat;

$(document).ready(function() {	
	
	//set initial radiobutton states
	$("#RankingSortContainer input").attr("checked", false);	
	$("#rblProductSize_0").attr("checked", "true");
		
	//set the on event behaviors of the controls
	BindBehaviors();
	
	//ie6 hack for transparent png background-images >.<
	if ($.browser.msie && $.browser.version == 6.0)
	{
		DD_belatedPNG.fix('.ArrowImageLeft');
		DD_belatedPNG.fix('.ArrowImageRight');
		DD_belatedPNG.fix('.balloonstyle');
		DD_belatedPNG.fix('.BalloonBottom');
		DD_belatedPNG.fix('.BalloonContent');
		$(".BalloonBottom").css("padding-bottom", "30px");
	}	

	//set up modal dialog
	//SetUpModal();
	
});


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: 425,
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;
}

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()
           
        }
    });
    
 document.getElementById("ctch").style.display = "none";

}


function BindBehaviors()
{		
	$("#rblProductSize > input").click(function() {
		SortAndFilterStyles();
	});	
	
	/*in ie, when the the on change event of a set of radiobuttons is fired, the selcted radiobutton value is incorrect
	(for whatever reason, ie sets the selected value to the radiobutton that was clicked before the click that fired the
	current on change. consequently, we must keep track of the selected radiobutton and use the onclick event instead :( */
	$("#RankingSortContainer > * > input").click(function() {
		if ($(this).attr('id') != SelectedRadioButton)
		{
			SelectedRadioButton = $(this).attr('id');
			SortAndFilterStyles();
		}		
	});	
}

function ShowPreview(LinkIndex, Link)
{
	var ProductId = Link.rel;
	var TimeoutId = setTimeout(function(){
	//show the color/size preview
	var Row = Math.floor(LinkIndex / 5);
	var Column = LinkIndex % 5 + 1;	
	PreviewBalloon = $("#" + ProductId);
	
	PreviewBalloon.addClass("BalloonWrapperShow");
	if (Column < 4)
		PreviewBalloon.css("left", Column * 160 + "px");
	else if (Column == 5)
		PreviewBalloon.css("left", "450px");
	else
		PreviewBalloon.css("left", "290px");
	
	PreviewBalloon.css("top", Row * 344 + "px");	
	
	if ($("#" + ProductId + " .BalloonCenteringDiv .LoadingGif").size() == 1)
		$("#" + ProductId + " .balloonstyle .BalloonContent").load("http://" + location.host + "/color/" + Link.rel + ".html", function(){ AjaxType = "PreviewLoad"; });		
	}, 1);
	QuickSelectTimeoutBag[ProductId + "inLink"] = { 'ProductId' : ProductId, 'TimeoutId' : TimeoutId };}

function HidePreview(ProductId)
{
	var TimeoutId = setTimeout(function(){
		//hide the size/color preview
		$("#" + ProductId).removeClass("BalloonWrapperShow");
	}, 1);
	QuickSelectTimeoutBag[ProductId + "outLink"] = { 'ProductId' : ProductId, 'TimeoutId' : TimeoutId };
}

function ArrowImageMouseOut(ProductId)
{
	HidePreview(ProductId);
}

function ArrowImageMouseOver(ProductId)
{
	clearQuickSelectTimeouts([ProductId + "outLink"]);
}

function SortAndFilterStyles()
{	
	var ControlStateObject = GetSortControlsState();
	var silmainbox = $("#silmainbox");
	silmainbox.html("<div style='text-align:center;width:100%;'><img src='../../Images/loading.gif' /><br /><span class='LoadingText'>Loading...</span></div>");
	silmainbox.load(location.href + "&CallbackType=AjaxSort", ControlStateObject, function(){ AjaxType = "Sort"; });		
}

function GetSortControlsState()
{
	var selectedSize = "";
	var SortType = "";

	//get selected size
	$("#rblProductSize > input").each(
		function (index)
		{
			if (this.checked)
			{
				selectedSize = $("#rblProductSize > label")[index].innerHTML;
				return false;
			}			
		}
	);	
	
	if (selectedSize == "All sizes")
		selectedSize = "";
		
	//get sort type	
	switch (SelectedRadioButton)
	{
		case "rblSort_0":
			SortType = "PriceAscending";
			break;
		case "rblSort_1":
			SortType = "PriceDescending";
			break;
		case "rblSort_2":
			SortType = "Rating";
			break;
		case "rblSort_3":
			SortType = "New";
			break;
		default:
			SortType = "";
			break;
	}
	
	var ControlStateData = {"SortType": SortType, "SelectedSize" : selectedSize};
	
	return ControlStateData;
}

function SetUpModal()
{
	//select all the a tag with name equal to modal
	$('a[name=modal]').click(function(e) {
		//Cancel the link behavior
		e.preventDefault();
		
		//Get the A tag
		var id = $(this).attr('href');
	
		//Get the screen height and width
		var maskHeight = $(document).height();
		var maskWidth = $(window).width();
	
		//Set heigth and width to mask to fill up the whole screen
		$('#mask').css({'width':maskWidth,'height':maskHeight});
		
		//internet explorer renders position:fixed wrong >.<
		if ($.browser.msie)
			$("#mask").css("position", "absolute");
			
		
		
		//Set the vertical position of the dialog
		
		var dialogTop = $(window).scrollTop() + 250;
		
		
		//transition effect		
		$('#mask').fadeIn(1000);	
		$('#mask').fadeTo("slow",0.8);	
	
		//Get the window height and width
		var winH = $(window).height();
		var winW = $(window).width();
              
		//Set the popup window to center
		//$(id).css('top',  winH/2-$(id).height()/2);
		$(id).css({'top':dialogTop});
		$(id).css('left', winW/2-$(id).width()/2);
	
		//transition effect
		$(id).fadeIn(2000); 
	
	});
	
	//if close button is clicked
	$('.window .close').click(function (e) {
		//Cancel the link behavior
		e.preventDefault();
		
		$('#mask').hide();
		$('.window').hide();
	});		
	
	//if mask is clicked
	$('#mask').click(function () {
		$(this).hide();
		$('.window').hide();
	});			
}

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);
			}
		}		
	}
}
