jQuery(document).ready(function($) {

	/////////////// DROPDOWNS ///////////////


	//COLORS

	function createColorDropDown(source,txt){
	  var selected = source.find("option[selected]");  // get selected <option>
	  var options = $("option:not(:first)", source);  // get all <option> elements
		var col = selected.attr("rel");
	  // create <dl> and <dt> with selected value inside it
		//get text to show initially
		var iniTxt;
		if(selected.val() == 'false' || selected.length == 0)
		{ 
			iniTxt = txt;
		} else
		{
			iniTxt = selected.text();
		}
	  $("#hat-options form").prepend('<dl id="'+source.attr('class')+'" class="dropdown"></dl>')
	  $("#"+source.attr('class')).append('<dt><a>' + iniTxt + 
	      '<span class="value">' + selected.val() + 
	      '</span><span class="color"></span></a></dt>')
	  $("#"+source.attr('class')).append('<dd><ul></ul></dd>')
	  // iterate through all the <option> elements and create UL
	  options.each(function(){

	    $("#"+source.attr('class')+" dd ul").append('<li><a>' + 
	        $(this).text() + '<span class="value">' + 
	        $(this).val() + '</span><span class="color" style="background-image:url('+$(this).attr('rel')+');"></span></a></li>');
	  });
	  //adjust spacing on first item
	  $("#"+source.attr('class')+" dd ul li a").filter(':first').css({
	  	'padding-top':12,
	  	'margin-top':6
	  })

		$("#"+source.attr('class')+" dd ul").append('<li class="close"><a>CLOSE</a></li>');
		
		//if current pin then imitate click of corresponding element
		if(curColor != "")
		{
			var $cO = $('#hat-color dd ul li:contains("'+curColor+'") a');
			colorClick($cO,true);
		}
	}
	

	
	//SIZES
	
	function createSizeDropDown(source,txt){
	  var selected = source.find("option[selected]");  // get selected <option>
	  var options = $("option:not(:first)", source);  // get all <option> elements
	  // create <dl> and <dt> with selected value inside it
		//get text to show initially
		var iniTxt;
		if(selected.val() == 'false' || selected.length == 0)
		{ 
			iniTxt = txt;
		} else
		{
			iniTxt = selected.text();
		}
	  $("#hat-options form").prepend('<dl id="'+source.attr('class')+'" class="dropdown"></dl>')
	  $("#"+source.attr('class')).append('<dt><a><span class="size-text init-size">' + iniTxt + 
	      '</span><span class="value">' + selected.val() + 
	      '</span><span class="size"></span></a></dt>')
	  $("#"+source.attr('class')).append('<dd><ul></ul></dd>')
	  // iterate through all the <option> elements and create UL
	  options.each(function(){

	    $("#"+source.attr('class')+" dd ul").append('<li><a><span class="size-text">' + 
	        $(this).text() + '</span><span class="value">' + 
	        $(this).val() + '</span><span class="size">'+$(this).attr('rel')+'</span></a></li>');
	  });

	  //adjust spacing on first item
	  $("#"+source.attr('class')+" dd ul li a").filter(':first').css({
	  	'margin-top':6
	  })


	  //size chart
	  $("#"+source.attr('class')+" dd ul").append('<li class="size-chart"><a><span class="size-chart-text">Size Chart</span></a></li>');
		$("#"+source.attr('class')+" dd ul").append('<li class="close"><a>CLOSE</a></li>');
	}
	
	
	//PINS
	
	function createPinDropDown(source,txt){
	  var selected = source.find("option[selected]");  // get selected <option>
	  var options = $("option:not(:first)", source);  // get all <option> elements
	  // create <dl> and <dt> with selected value inside it
		//get text to show initially
		var iniTxt;
		if(selected.val() == 'false' || selected.length == 0)
		{ 
			iniTxt = txt;
		} else
		{
			iniTxt = selected.text();
		}
	  $("#hat-options form").prepend('<dl id="'+source.attr('class')+'" class="dropdown"></dl>')
	  $("#"+source.attr('class')).append('<dt><a><span class="pin-text init-size">' + iniTxt + 
	      '</span><span class="value">' + selected.val() + 
	      '</span><span class="image"></span><span class="pin-separate">Pin Sold Separateley</span></a></dt>')
			  $("#"+source.attr('class')).append('<div class="pin-container"><dd></dd></div>')
	
		//now create dropdowns for each category that will open when clicked
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>NFL</h4><div class="nfl pin-list"><div class="ul-fix"></div></div></div>');
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>NCAA</h4><div class="ncaa pin-list"><div class="ul-fix"></div></div></div>');
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>NHL</h4><div class="nhl pin-list"><div class="ul-fix"></div></div></div>');
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>NBA</h4><div class="nba pin-list"><div class="ul-fix"></div></div></div>');
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>MLB</h4><div class="mlb pin-list"><div class="ul-fix"></div></div></div>');
		$("#"+source.attr('class')+" dd").append('<div class="pin-list-holder"><h4>Other</h4><div class="other pin-list"><div class="ul-fix"></div></div></div>');
		
		function createPinList(cat)
		{
			//for each of the above, add list items to 
			$(".sport-pin option[rel='"+cat.toUpperCase()+"']").each(function() {
				var nm = $(this).text().split(" Pin")[0];
				if(pinsJSON[nm])
				{
					var img = pinsJSON[nm].image_url;
			    $("#"+source.attr('class')+" dd div."+cat+" .ul-fix").append('<div class="li-fix"><span class="v-center"><span class="pin-text"><p>' + 
			        $(this).text() + '</p></span></span><span class="value">' + 
			        $(this).val() + '</span><span class="image"><img src="'+baseURL+'scripts/timthumb.php?src='+img+'&h=200"/></span></div>');
				
				}
			})
		}
		createPinList('nfl');
		createPinList('ncaa');
		createPinList('nhl');
		createPinList('nba');
		createPinList('mlb');
		createPinList('other');
			
		//fix because now on every single dropdown (needs to be separate)
		$("#"+source.attr('class')).append('<div class="close"><a>CLOSE</a></div>');
		
		//if current pin then imitate click of corresponding element
		if(curPin != "")
		{
			var $cO = $('#sport-pin dd .ul-fix .li-fix:contains("'+curPin+'")');
			pinClick($cO,true);
		}
		
	}

	function setDDCorners(dd,te,hide)
	{
		if(!hide)
		{
	    dd.toggle();
	    if(dd.parent().parent().attr('id') == 'sport-pin')
	    {
	    	dd.parent().parent().find('.close').toggle();
	    	$('.pin-container').toggle();
	    	dd.css('display',$('.pin-container').css('display'));
				//show more pins arrows
				$('.more-pins').toggle();
				checkMorePins();
	    } else 
	    {
	    	
		    $('#sport-pin .close').hide();
	    }
		}
		if(dd.css('display') == 'block')
		{
			$('#hat-options').css({
				'z-index':55
			});
			te.css({
				'border-bottom-left-radius': 0,
				'border-bottom-right-radius': 0,
				'-moz-border-radius-bottomright': 0,
				'-moz-border-radius-bottomleft': 0
			})
			
			//if dd is pin list, reapply scrollers
			if(dd.children(':first-child').hasClass('pin-list-holder'))
			{
				setScrollPanes();
			}
		} else
		{
			$('#hat-options').css({
				'z-index':19
			});
			te.css({
				'border-bottom-left-radius': 10,
				'border-bottom-right-radius': 10,
				'-moz-border-radius-bottomright': 10,
				'-moz-border-radius-bottomleft': 10
			})
		}

		//always hide size chart
		$('#size-chart').hide();
	}

	function setScrollPanes()
	{
		/*jQuery.each(jQuery.browser, function(i, val) {
      alert(i+" : "+val);
    });*/
    //detect whether lion with safari
    //if, then don't change scrollbars from default
    //due to issues with new safari and "lazy" rendering
    if(jQuery.browser.safari)
    {
    	isLionSafari = true;
    	$('.pin-list').css({
    		'margin-top':4,
    		'margin-right':3,
    		'width':259,
    		'height':289
    	})
    } else
    {
			$("#sport-pin dd div.nfl").jScrollPane({showArrows:true,
																							verticalArrowPositions: 'after',
																							horizontalArrowPositions: 'after'});
			$("#sport-pin dd div.ncaa").jScrollPane({showArrows:true,
																							verticalArrowPositions: 'after',
																							horizontalArrowPositions: 'after'});
			$("#sport-pin dd div.nhl").jScrollPane({showArrows:true,
																							verticalArrowPositions: 'after',
																							horizontalArrowPositions: 'after'});
			$("#sport-pin dd div.nba").jScrollPane({showArrows:true,
																							verticalArrowPositions: 'after',
																							horizontalArrowPositions: 'after'});
			$("#sport-pin dd div.mlb").jScrollPane({showArrows:true,
																							verticalArrowPositions: 'after',
																							horizontalArrowPositions: 'after'});
    }
	}

	
	//
	//clicks for dds

	function colorClick(ele,init)
	{
		var text = ele.html();
		var col = ele.find('.color').css('background-image');
    $("#hat-color dd").hide();
		setDDCorners($("#hat-color dd"),$('#hat-color dt a'),true);
		
		//hide if close
		if(text == "CLOSE")
		{
			return;
		} 
		
		var par = ele.parent().parent().parent().parent();
		
	  par.find("dt a").html(text);
		par.find("dt a .color").css('background-image',col);
	
	  var source = $(".hat-color");
	  source.val(ele.find("span.value").html());

		//set hash to color
		curColor = $(".hat-color :selected").text();
		colorVal = $(".hat-color :selected").val();
		var col = curColor.replace(/ /g,'_');

	  //set pin initial text to show free pin
	  setInitPinText()
		
		if(!init)
		{
			window.location.hash = '!'+curModel.replace(/ /g,'_')+'/'+col+'/'+curPin.replace(/ /g,'_');
		} else
		{
			setHatColor();
		}
		
		//readd in remove hat
		if(par.find('.remove').length == 0 && curColor != "")
		{
	    var rem = par.prepend('<div class="remove"><a>Remove</a></div>');	
			rem.find('.remove').click(function() {
				//reset color dd
			  par.find("dt a").html(initColDDText);
				par.find("dt a .color").css('background-image','none');
				par.find("dt a .value").text('');
				
				//reset size dd
				$('#hat-size').find('dt a .size-text').text(initSizeDDText);
				$('#hat-size').find('dt a .size-text').addClass('init-size');
				$('#hat-size').find('dt a .size').text('');
				$('#hat-size').find('dt a .value').text('');
				$('#hat-size').find("dt a").removeClass('dd-arrow-hide');
				
			
				//reset actual dropdown
				jQuery(".hat-size option:selected").removeAttr('selected');
				//reset actual dropdown
				jQuery(".hat-color option:selected").removeAttr('selected');

				//set hash to nothing
				curColor = "";
				curSize = "";
				colorVal = "";
				window.location.hash = '!'+curModel.replace(/ /g,'_')+'/'+curColor+'/'+curPin.replace(/ /g,'_');

						
			  //set pin initial text to remove free pin
			  setInitPinText()
				
				//remove hat from main models
				var i = 1;
				$('#hat-models').find('.hat-model').each(function() {
					$(this).find('.models-hat').remove();
					i++;
				})
				
				//finally, remove this
				$(this).remove();
			})
		}
	}
	
	function sizeClick(ele)
	{	
		var text = ele.find('.size-text').text();
		var siz = ele.find('.size').text();
		//hide if close
		if(ele.text() == "CLOSE")
		{
	    $("#hat-size dd").hide();
			setDDCorners($("#hat-size dd"),$('#hat-size dt a'),true);
			return;
		} 

		if(ele.parent().hasClass('size-chart'))
		{
			return;
		}
		$('#hat-size dd').hide();
		setDDCorners($("#hat-size dd"),$('#hat-size dt a'),true);
		var par = ele.parent().parent().parent().parent()
	  par.find("dt a .size-text").html(text);
		par.find("dt a .size-text").removeClass('init-size');
		par.find("dt a").addClass('dd-arrow-hide')
		par.find("dt a .size").html(siz);
	
	  var source = $(".hat-size");
	  source.val(ele.find("span.value").html());
	
		//set global size values
		curSize = $(".hat-size option:selected").text();
		sizeVal = $(".hat-size option:selected").val();
		
	}

	function setInitPinText()
	{
		if(curColor != "")
		{
			//change pin to read "Free Pin With Hat" and $0
			//change text if pin currently not selected
			$('#sport-pin .init-size').text(initPinDDText2);
			$('#sport-pin .pin-separate').text(initPinSubText2);
		} else
		{
			//change pin to read "Pin Sold Seperately" and $8
			$('#sport-pin .init-size').text(initPinDDText);
			$('#sport-pin .pin-separate').text(initPinSubText);
		}
	}
	
	function pinClick(ele,init)
	{
		var text = ele.find('.pin-text p').text();
		var img = ele.find('.image img').attr('src');
		//hide if close
		if(ele.text() == "CLOSE")
		{
	    $("#sport-pin dd").hide();
	    $("#sport-pin .close").hide();
	    $('.more-pins').hide();
	    $('.pin-container').hide();
			setDDCorners($("#sport-pin dd"),$('#sport-pin dt a'),true);
			return;
		} 
		var par;
		if(init)
		{
			par =	ele.parent().parent().parent().parent().parent().parent().parent();
		} else
		{
			par = ele.parent().parent().parent().parent().parent().parent().parent().parent().parent();
		}
	  par.find("dt a .pin-text").html(text);
		par.find("dt a .pin-text").removeClass('init-size');
		//par.find("dt a .pin-separate").remove();
		par.find('dt a .pin-separate').css('font-size','10px');
		setInitPinText();
		par.find("dt a").addClass('dd-arrow-hide');
		//make sure img element exists
		var imgEle = par.find("dt a .image img");
		if(imgEle.length == 0)
		{
			par.find("dt a .image").append('<img style="height:30px;"/>');
		}
		par.find("dt a .image img").attr('src',img);
		
		$('#sport-pin dd').hide();
    $('.pin-container').hide();
    $("#sport-pin .close").hide();
    $('.more-pins').hide();
		setDDCorners($("#sport-pin dd"),$('#sport-pin dt a'),true);
	
		//set original dropdown
	  var source = $(".sport-pin");
	  source.val(ele.find("span.value").text());

	
		
		//set hash to pin
		curPin = $(".sport-pin option:selected").text();
		pinVal = $(".sport-pin option:selected").val();
		
		if(!init)
		{
			window.location.hash = '!'+curModel.replace(/ /g,'_')+'/'+curColor.replace(/ /g,'_')+'/'+curPin.replace(/ /g,'_');
		} else
		{
			setPin();
		}
	
	//add in remove link
		if($('#sport-pin').find('.remove').length == 0 && curPin != "")
		{
	    var rem = $('#sport-pin').prepend('<div class="remove"><a>Remove</a></div>');	
			rem.find('.remove').click(function() {
				//reset pin dropdown
				var dt = par.find('dt a .pin-text');
				dt.addClass('init-size');

				var pT;
				if(curColor != "")
				{
					pT = initPinSubText2;
				} else
				{
					pT = initPinSubText;
				}
 				//dt.after('<span class="pin-separate">'+pT+'</span>');
				dt.parent().find('.pin-separate').css('font-size','12px');
				dt.text(initPinDDText);
				//remove image element
				par.find('dt a .image img').remove();
			
				//reset actual dropdown
				jQuery(".sport-pin option:selected").removeAttr('selected');

				//set hash to nothing
				curPin = "";
				pinVal = "";
				window.location.hash = '!'+curModel.replace(/ /g,'_')+'/'+curColor.replace(/ /g,'_')+'/'+curPin;

				setInitPinText();
				
				//remove pin from main models
				var i = 1;
				$('#hat-images').find('.hat-image').each(function() {
					$(this).find('.models-pin').remove();
					i++;
				})
				
				//finally, remove this
				$(this).remove();
			})
		}
	}
	
	
	function hideOthers(cur)
	{
		$('.dropdown dt a').each(function() {
			if($(this) != cur)
			{
				var $ul = $(this).parent().parent().find('dd');
				$ul.hide();
		    if($ul.parent().parent().attr('id') == 'sport-pin')
		    {
		    	$ul.parent().find('.close').hide();
			    $('.more-pins').hide();
		    }
				setDDCorners($ul,$(this),true)
			}
		})
	}

	//for changing when clicking something else
	$(window).hashchange(function() {
		if(curColor != "" && !isSnowboard)
		{
			var $cO = $('#hat-color dd ul li:contains("'+curColor+'") a');
			colorClick($cO,true);	
		}
		
		if(curPin != "" && !isSnowboard)
		{
			var $cO = $('#sport-pin dd .ul-fix .li-fix:contains("'+curPin+'")');
			pinClick($cO,true);
		}
	});


	//
	//now initialize all drop downs
	
	if(!isSnowboard && !isOtherProducts)
	{
		createPinDropDown($('.sport-pin'),initPinDDText);
		
		$("#sport-pin dt a").click(function() {
			hideOthers($(this))
			setDDCorners($(this).parent().parent().find('dd'),$(this))
		});
	}

	if(!isOtherProducts)
	{	
		//always create size
		createSizeDropDown($('.hat-size'),initSizeDDText);

		$("#hat-size dt a").click(function() {
			hideOthers($(this))
			setDDCorners($(this).parent().parent().find('dd'),$(this))
		});
		
		if(!isSnowboard)
		{
			createColorDropDown($('.hat-color'),initColDDText);
			//
			//set up click events for selected values
			
			$("#hat-color dt a").click(function() {
				hideOthers($(this))	
				setDDCorners($(this).parent().parent().find('dd'),$(this))
			});
			
		}

		//check price for current settings
		checkPrice();
	}
	
	
	//now that created new elements, can assign events to them
	
	
	
	//
	//and clicks for all dropdown list elements
	
	$("#hat-color dd ul li a").click(function() {
	    colorClick($(this));
	});
	
	$("#hat-size dd ul li a").click(function() {
	    sizeClick($(this));
	});
	
	$("#sport-pin dd .li-fix").click(function() {
	    pinClick($(this));
	});
	
	//also close for pin dd
	$('#sport-pin .close a').click(function() {
		pinClick($(this));
	})

	//hat size click
	$('#hat-size li.size-chart a').click(function() {
		$('#size-chart').show();
	})
	
	
	//make sure if click out of dds, then they go away
	$(document).bind('click', function(e) {
	    var $clicked = $(e.target);
	    if (!$clicked.parents().hasClass("dropdown") && !$clicked.parents().hasClass('more-pins') || $clicked.hasClass('pin-container') || $clicked.hasClass('pin-list'))
			{
        $(".dropdown dd").hide();
		    $('#sport-pin .close').hide();
		    $('.more-pins').hide();
		    $('.pin-container').hide();
				setDDCorners($(".dropdown dd"),$('.dropdown dt a'),true);
			}
	});
	








	var curPinPosition = 0;
	var isPinAnimating = false;
	var pinMoveDist = -262*2;
	//scroll for pins
	$('#sport-pin dd .ul-fix').mouseover(function() {
		//see if off page and if so, then move over 
		if($(window).width()-($(this).offset().left+$(this).width())<10)
		{
			if(!isPinAnimating)
			{
				curPinPosition = Math.min(curPinPosition+1,$('#sport-pin dd .ul-fix').length-1);
				var cp = pinMoveDist*curPinPosition+pinOffset;
				isPinAnimating = true;
				$('#sport-pin dd').animate({'margin-left':cp},500,function() {
					function isPA()
					{
						isPinAnimating = false;
					}
					setTimeout(isPA,500);
					checkMorePins();
				})
			}
		} else if($(this).offset().left<20)
		{
			if(!isPinAnimating)
			{
				curPinPosition = Math.max(curPinPosition-1,0);
				var cp = pinMoveDist*curPinPosition+pinOffset;
				isPinAnimating = true;
				$('#sport-pin dd').animate({'margin-left':cp},500,function() {
					isPinAnimating = false;
					checkMorePins();
				})
			}
		}
	})

	function checkMorePins()
	{
		var $sp = $('#sport-pin dd');
		var n = $(window).width()-(Number($sp.css('margin-left').split('px')[0])+$sp.width());
		if(n>10)
		{
			$('.more-pins-next').hide();
		} else
		{
			$('.more-pins-next').show();
		}
		if(Number($sp.css('margin-left').split('px')[0])>0)
		{
			$('.more-pins-prev').hide();
		} else
		{
			$('.more-pins-prev').show();
		}
	}

	//more pin arrow buttons
	$('.more-pins-next').click(function() {
		curPinPosition = Math.min(curPinPosition+1,$('#sport-pin dd .ul-fix').length-1);
		var cp = pinMoveDist*curPinPosition+pinOffset;
		$('#sport-pin dd').animate({'margin-left':cp},500,function() {
			function isPA()
			{
				isPinAnimating = false;
			}
			setTimeout(isPA,500);
			checkMorePins();
		})
	})

	$('.more-pins-prev').click(function() {
		curPinPosition = Math.max(curPinPosition-1,0);
		var cp = pinMoveDist*curPinPosition+pinOffset;
		isPinAnimating = true;
		$('#sport-pin dd').animate({'margin-left':cp},500,function() {
			isPinAnimating = false;
			checkMorePins();
		})
	})



	
	
	

});
