$(document).ready(function(){
	$('select.filter').change(function(){
		$('form#productFilter').submit();
	});
		
	$('select#homeladiesbrands').change(function(){
		if($(this).val() != "0"){
			window.location = $(this).val();
		}
	});
	
	$('select#homemensbrands').change(function(){
		if($(this).val() != "0"){
			window.location = $(this).val();
		}
	});
	$('.showmenu').click(function(){
		$('.' + $(this).attr('rel')).slideToggle('fast');				
		return false;
	});	
	$('.subitem').hide();
	$('.' + $('.displayItems').attr('rel')).show();
	
	$("select#search_gender").change(function(){
              $.getJSON("/cfc/search.cfc",{ID : $(this).val(), method : 'funcGetBrands', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_brand');				
            });                
    }).change(function(){
              $.getJSON("/cfc/search.cfc",{ID : $(this).val(), method : 'funcGetShoeTypeByGender', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_shoetype');
            });                
    });
	
	$("select#search_brand").change(function(){
              $.getJSON("/cfc/search.cfc",{ID: $("select#search_gender").val(),BrandID : $(this).val(), method : 'funcGetShoeTypeByBrand', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_shoetype');
            });                
    }).change(function(){
              $.getJSON("/cfc/search.cfc",{ID: $("select#search_gender").val(),BrandID : $(this).val(),TypeID: $("select#search_shoetype").val(), method : 'funcGetShoeSizes', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_shoesize');
            });                
    });
	$("select#search_shoetype").change(function(){
              $.getJSON("/cfc/search.cfc",{ID: $("select#search_gender").val(),BrandID : $("select#search_brand").val(),TypeID : $(this).val(), method : 'funcGetShoeSizes', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_shoesize');
            });                
    }).change(function(){
              $.getJSON("/cfc/search.cfc",{ID: $("select#search_gender").val(),BrandID : $("select#search_brand").val(),TypeID : $(this).val(), method : 'funcGetShoeWidths', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_width');
            });                
    }).change(function(){
              $.getJSON("/cfc/search.cfc",{ID: $("select#search_gender").val(),BrandID : $("select#search_brand").val(),TypeID : $(this).val(), method : 'funcGetShoeColours', returnformat : 'json', queryformat : 'column' }, function(j){
                setoptions(j,'search_colour');
            });                
    });
	
	function setoptions(j,list){
		var options = '';
		options += '<option value="x">Any</option>';				  
		for (var i=0; i<j.ROWCOUNT; i++) {
			options += '<option value="' + j.DATA.ID[i] + '">' + j.DATA.LABEL[i] + '</option>';				  
		}
        
        $("select#"+list).html(options);
        $("option:first", "select#"+list).attr("selected","selected");            
	}
	
	$('#samedelivery').click(function(){		
		if($(this).is(':checked')){			
			var address = "";
			$('#billingdetails .inputField').each(function(){				
				var type = this.type, tag = this.tagName.toLowerCase();				
				 if (type == 'text' || tag == 'textarea')
				   address += this.value + '<br />';				 
				 else if (tag == 'select')
				   address += this.options[this.options.selectedIndex].text + '<br />'; 			
			});
			if (address.length > 0) {
				$('#deliveryaddresscont').html('<p>' + address + '</p>');
				$('#deliveryaddform').fadeOut('slow',function(){
					$('#deliveryaddresscont').fadeIn('slow');
					});
			}
		}else{
			$('#deliveryaddresscont').fadeOut('slow',function(){
				$('#deliveryaddform').fadeIn('slow');	
			});			
		}
	});
	
	$('#ChangeCountry').click(function(){
		$(this).hide();
		$('select#delcountry').show();
		return false;
	});
	
	$('select#delcountry').change(function(){
		var selectedname = this.options[this.options.selectedIndex].text;
		$('input#delcountryid').val($(this).val());
		$.getJSON("/cfc/shopping.cfc",{country: $(this).val(), cnt : $('input#itemCnt').val(), method : 'funcGetCountryCosts', returnformat : 'json', queryformat : 'column' }, function(j){  
				if(j.ROWCOUNT > 0){
					var sub = parseFloat($('#subtotal').html());
					var discount = parseFloat($('#discount').html());
					var subtotal = sub-discount;
					var delcost = 0;
					var rate = parseFloat(j.DATA.CURRENCYRATE[0]);
					if(parseFloat(j.DATA.SHIPPINGCOSTS[0]) > 0){
						delcost = parseFloat(j.DATA.SHIPPINGCOSTS[0])						
					}
					subtotal += delcost;
					delcost = Math.round(delcost*rate*100)/100;
					subtotal = Math.round(subtotal*rate*100)/100;
					var tLabel = j.DATA.CURRENCYSYMBOL[0] + subtotal;
					if (parseInt(j.DATA.VAT[0]) > 0) {
						tLabel += ' <i>(inc VAT)</i>';
						$('#totalcost').html(tLabel);
					}else{
						$('#totalcost').html(tLabel);
						tLabel = ' (VAT deducted at payment if billing to same location)';	
						$('#vatMessage').html('<p class="pad linespace">'+tLabel+'</p>');
					}
					$('#delcost').html(j.DATA.CURRENCYSYMBOL[0] +delcost + '<i>('+selectedname+')</i>');					
				}              
				$('select#delcountry').hide();
				$('#ChangeCountry').show();
            });                
		
		return false;
	});
	
	if ($('#savedetails').is(':checked')){
			$('#passwordCont').show();
		}else{
			$('#passwordCont').hide();	
		}
		
	$('#savedetails').click(function(){
		if ($(this).is(':checked')){
			$('#passwordCont').show();
		}else{
			$('#passwordCont').hide();	
		}
	});
		
	
	$('.formAddProduct').submit(function(){	
		$.post("/cfc/shopping.cfc?method=funcAddToBasketR",{post: $(this).serialize()}, function(j){ 
			var bid = $.cookie('BASKETID');
			$('input#basket').val(bid);
			var d = new Date();
			var randN = Math.round(((new Date()).getTime()-Date.UTC(1970,0,1))/1000) + Math.floor(Math.random()*11);
			
			$.ajax({
			  url: "/cfc/shopping.cfc",
			  global: false,
			  cache: false,
			  type: "POST",
			  data: ({ method : 'funcCheckBasket','nt': randN, 'id' : bid, returnformat : 'json', queryformat : 'column' }),
			  dataType: "json",
			  success: function(j,k){ 
				$('span.basketitems').html(j.DATA[0][12]);

				var t = $.template('<div id="flashBasket"><h2>Your Basket</h2><div class="flashInfo"><p class="added">This product has been successfully added to your basket.</p><img src="/picstore/products/thumbnail_${prodImage}" width="50" alt="${prodStyle}" border="0" /><h3>${prodBrand}</h3><p>Style: <span>${prodStyle}</span><br/>Colour: <span>${prodColour}</span><br/>Size: <span>${prodSize}</span><br />Fitting: <span>${prodFitting}</span><br/>Price: <span>${strCost}</span></div></div>');
				$('#header').after(t, {
								prodImage: j.DATA[0][13],
								prodStyle: j.DATA[0][9],
								prodBrand: j.DATA[0][11],
								prodColour: j.DATA[0][5],
								prodSize: j.DATA[0][2],
								prodFitting: j.DATA[0][3],
								prodCost: Math.round(j.DATA[0][6]*100)/100,
								strCost: j.DATA[0][16]
							});
				$('#flashBasket').stop(true, true).animate({opacity: "show"});
				 setTimeout(function() {
            		$('#flashBasket').animate({opacity: "hide"}, "fast") },
				 5000);				 
				 t = "";
				 }
			});
		});
		$('#flashBasket').remove();
		return false;
	});
	
	try {
		$("body select.drpCurrencyTop").msDropDown({useSprite:'sprite',showIcon:false,setWidth:17,widthMethod:'pos'});
		//alert($.msDropDown.version);			
		} catch(e) {
			//alert("Error: "+e.message);
		}
	try {
		$("body select.drpCurrencyCol").msDropDown({useSprite:'sprite',showIcon:false,setWidth:33,widthMethod:'neg'});
		//alert($.msDropDown.version);			
		} catch(e) {
			//alert("Error: "+e.message);
		}	
		$("body select.drpCurrency").change(function(){
			$('form#form_currency #currencypath').val(location.href);
			$('form#form_currency').submit();
			/*$.getJSON("/cfc/currency.cfc",{code: $(this).val(), method : 'funcSetCurrency', returnformat : 'json', queryformat : 'column' }, function(j){  
				if(j.ROWCOUNT > 0){
					var rate = parseFloat(j.DATA.rate[0]);	
					var unicode = j.DATA.unicode[0];
					$('.currencyflag').removeClass(j.DATA.previouscode[0]).addClass(j.DATA.code[0]);
					$('#content span.unicodestr').each(function(i){
						$(this).html(unicode);
					});	
					$('#content span.pricestr').each(function(i){
						var currPrice =  parseFloat($(this).html());
						if(currPrice > 0){
							var cost = Math.round(currPrice*rate*100)/100;
							$(this).html(cost);
						}
					});			
				}              				
            });                
		
			return false;*/
		});
		
		
		$('#drpCurrency_child').css('position','absolute');
		$('#drpCurrency_child a:first').css('margin-top','8px');
		$('#searchBox').show();
		$('#searchLink').toggle(function() {
		  $('#searchBox').hide();
		  return false;
		}, function() {
		  $('#searchBox').show();
		  return false;
		});
			
});