﻿/*
Edited: 30 October 2009 (DAB @ 11:19)
Website: 
Created: 22 February 2008
Author: Andrew Keats

NOTE: These scripts are based on jQuery 1.2.3 though they are working with jquery 1.2.6 and should work ok
*/

// Selects the first delivery type on hawkins and stocking fillers
$(document).ready(function(){ 
    if ($('#delivery-type', '#delivery-details').length && (whiteLabel == 'HawkinsBazaar' || whiteLabel == 'StockingFillers')) {
        $('TD:last input' , '#delivery-type .delivery-options').attr('selected', '').attr('checked', '');
        $('TD:first input' , '#delivery-type .delivery-options').attr('selected', 'selected').attr('checked', 'checked');
    }
});

$(document).ready(function(){ 
	$('body').click(function(e) {
	if( $(e.target).is('input[id$="personaliseProduct2"]')) {
	
	}	
  })
 });

// overlay iframe fix for IE (tackles overlay issue for dropdowns and form elements)
$(document).ready(function(){ 
	if ( $.browser.msie && /6.0/.test(navigator.userAgent) ){
		$.getScript("/assets/letterbox/scripts/jquery.bgiframe.min.js");
	}
}); 

// PNG fix
//$(document).ready(function(){ 
	//$(document).pngFix(); 
//}); 

$(document).ready(function(){
	// this is for the more section of primary nav
	/*$("li.more>a").click(function () {
		$("#more-submenu").toggle();
	});*/
	
	// invoking the carousel
	if ($('#carousel').length > 0) {
		$.getScript("/assets/hawkinsBazaar/scripts/jcarousellite_1.0.1.min.js", function()
			{
				window.setTimeout(function()
				{
					var carouselWrap = '<div class="carousel-outer"><div></div></div>';
					var prevBtn = '<div class="prev"></div>';
					var nextBtn = '<div class="next"></div>';
					var secs = 1000
					$('#carousel').wrap(carouselWrap).parent(carouselWrap).prepend(prevBtn).append(nextBtn);
					$('.carousel-outer').show("slow");
					$('#carousel').css('display', 'block');
					$('#carousel').jCarouselLite({
						btnNext: "div.next",
						btnPrev: "div.prev",
						visible: 8,
						scroll: 4,
						auto: 40*secs,
						speed: 1.5*secs
					});

					// this shows the carousels once content is loaded
					//$('#carousel').css('display','block').addClass('show');
					//$('.carousel-outer').addClass('show').show();
				}, 250); 
			}
		);
	}
	// this is for top-nav
	$('#site-navigation ul.catagories li').each(function() {
		if ($(this).children('ul').length > 0) {

			$('#site-navigation ul.catagories li ul.sub-cat li:odd').children('a').addClass("even");
			$(this).hover(
				function() {
					$(this).addClass("active");
					$(this).children('ul').addClass("active");
					if ($.fn.bgiframe){
						$(this).children('ul').bgiframe();
					}
					if ($.browser.mozilla) {
						var cat = $(this);
						//console.log('Im hovered ' +cat);
						$('input[@type="text"], input[@type="password"]', '#site-navigation').mouseover( function(){
							$(cat).removeClass("active");
							$(cat).children('ul').removeClass("active");
						});
					}
					else return;
					},
				function() {
					$(this).removeClass("active");
					$(this).children('ul').removeClass("active");
					}
			);
		}
	});
	

	// clearing inputfields automatically and restoring them if nothing is entered
	//creating the condition which checks for any inputs of the correct type
	//if ($('input.textfield').length > 0 ){
	if ($('input.textfield, textarea').length > 0 ){
		//creating the array to keep data in
		swapValues=[];
		// running the functions individually through any inputs found using 'each' to bind functions
		//$("input.textfield").not('.no-change').each(
		$("input.textfield, textarea").not('.no-change').each(
			// the function is given a number
			function(i){
				// the number also applies to the 'nth' variable for the array and stores the default text
				swapValues[i]=$(this).val();
				$(this).focus(function(){
					if($(this).val()==swapValues[i]){
					$(this).val("")
					}
				}
				).blur(function(){
					if($.trim($(this).val())==""){
						$(this).val(swapValues[i])
					}
				});
			}
		);
	}
	// converting lists to drop down menus
	function listConverter(list){
		// running a function on each list item with a nested anchor
		$(list).children('li a').each( function () {
			var linkValue = $(this).find('a').attr('href');
			var nameValue = $.trim($(this).find('a').text());
			var newOption = $("<option value='' />").text(nameValue).val(linkValue + ' ');
			$(this).replaceWith(newOption);
		});
		// changing all the list elements to select elements
		$(list).each( function () {
			var newSelect = $("<select>" + $(this).html() + "</select>");
			$(this).replaceWith(newSelect);
		});
	};
	//
	//making the header the default selected select element
	function headerInclude(listContainer , hType){
		if ($(listContainer).find(hType)){
			$(listContainer).find(hType).each( function(){
				var headerText = $(this).text();
				var optSelected = $("<option value='' selected='selected'></option>").text('Any ' + headerText).attr({ selected:"selected", value: ""});
				$(this).next('select').prepend(optSelected);
				$(this).remove();
			});
			if ( $.browser.msie ) {
				$(listContainer).find('select').each( function() {
			   		$(this).find('option').eq(0).attr({selected: "selected"});
			   	});
			}
		}
		if ($(listContainer).children('.selected')){
			$(listContainer).children('.selected').each( function() {
				var returnValue = $(this).children('select').children('option:last-child').val();
				$(this).children('select').children('option:first-child').val(returnValue);
				$(this).children('select').children('option:last-child').val('').attr('selected','selected');
			});
		}
	}
	//
	//convert one element to another in a defined parent element
	function elemToElem(whereFrom, whatFrom, whatTo){
		if($(whereFrom).find(whatFrom).length > 0){
			$(whereFrom).find(whatFrom).each( function(){
				var copyText = $(this).text();
				var theElem = $('<'+ whatTo + '></' + whatTo + '>').text(copyText);
				$(this).replaceWith(theElem);
			});
		}
	}
	//
	//switching two elements position
	function tradingPlaces(parentElem, switchElem, pivotElem) {
		$(parentElem).each( function () {
			if($(this).length > 0 && $(this).children(switchElem).length > 0 && $(this).children(pivotElem).length > 0){
				$(this).children(switchElem).appendTo(this);
				$(this).children(pivotElem).prev().remove(switchElem);
			}
		});
	}
	//
	//
	// creating auto-navigating dropdown menus
	function activeOptions(listContainer){
		$(listContainer +" select").each( function () {
			$(this).change(function () {
				if ($(this).val() != ''){
					var goToLink = $(this).attr("value");
					window.parent.location = goToLink;
				}
			});
		});
	};
	//
	//adding browser specific classes for the refine areas
	function refineFix(container) {
		if ($.browser.safari) {
			$(container).addClass('safari');
			if ($.browser.mozilla && $.browser.opera) {
			$(container).removeClass('safari').addClass('chrome');
			}
		}
		else if ($.browser.opera) {
			$(container).addClass('opera');
		}
		else {
		}
	}
	//
	//resizing the list widths for the side refine price box
	function refineListWidths (listContainer) {
		var listLength = ($(listContainer).children('li').length);
		var listEvenOdd = listLength % 2;
		// odd number of list items
		if (listLength > 2 && listEvenOdd == 1){
			$(listContainer).children('li:last').prevAll().removeClass('whole').addClass('half');
		}
		// even number of list items
		else if (listLength > 2 && listEvenOdd == 0){
			$(listContainer).children('li:last').prevAll().removeClass('whole').addClass('half');
			$(listContainer).children('li').eq(3).prevAll().removeClass('half').addClass('third');
		}
	};
	//
	//matching the per page option to the number of items displayed
	function alignPerPage (listLocation, pagingLocation) {
		var numberBand;
		var listLength = $(listLocation).children('li.product').length;
		if (16 < listLength && listLength <= 24) {
			$(pagingLocation).each(function(){
			$(this).find("option").eq(3).attr("selected","selected");
			});
		}
		else if (12 < listLength && listLength <= 16) {
			$(pagingLocation).each(function(){
			$(this).find("option").eq(2).attr("selected","selected");
			});
		}
		else if (8 < listLength && listLength <= 12) {
			$(pagingLocation).each(function(){
			$(this).find("option").eq(1).attr("selected","selected");
			});
		}
		else {
			$(pagingLocation).each(function(){
			$(this).find("option").eq(0).attr("selected","selected");
			});
		}
	}
	//
	// invoke the auto-navigating dropdown options, the converting of link lists to active dropdowns, switching the p descriptor to a label 
	if ($('.paging').length > 0) {
		//tradingPlaces('.panel','div.per-page','.sort-options');
		listConverter('.paging-options ul');
		listConverter('.refine ul');
		headerInclude('.refine', 'h4');
		if ($('.sort-options').children('select')) {
			$('.sort-options select').each( function() {
				$(this).prepend('<option value="#" selected="selected">Please Select</option>');
			   	$(this).find('option').eq(0).attr({selected: "selected"});
			}); 
		};
		$('.paging').show('slow');
		activeOptions('.paging.options');
		elemToElem('.paging-options', 'p', 'label');
		alignPerPage('#category-list ul', 'div.per-page');
		refineFix('.refine');
	}
	// invoke refine list width mod 
	//!!not being used any more because this part of the design is flawed 
	//!!and doesn't work well with many characters
	/*if ($('#side-refine').length > 0) {
		refineListWidths('#side-refine ul');
	}*/
	/*if($('#carousel').length > 0){
		$('#carousel').addClass('show');
	}*/
	//end 
	
	/*Focus on PersonalShopper postcode input and QuickOrderForm product code input, only when there's no value in the field*/
	$('.give-focus:not([value])').focus();
});


//Paypal - Credit card selection on payment page
$(document).ready(function() {
      
        $('#PayPalPaymentSelection').click(function() {
            $('#creditcardpayment-details').slideUp();
            $('#paypalpayment-details').slideDown();
            
            return true;
        });

        $('#CreditCardPaymentSelection').click(function() {
            $('#creditcardpayment-details').slideDown();
            $('#paypalpayment-details').slideUp();
            
            return true;
        });
   
});
		
$(document).ready(function(){
	function makeGridList(element, numCols) {
		var gridRowHolder = $("<div class='gridRowHolder'></div>").insertAfter(element);			// a container for the new ULs
		$(element).children("li").each(function(i) {
				  $(this).css("min-height", "0");			// get rid of min-height
				  if (i % numCols == 0) {
								$("<ul class='clearfix products gridRow'></ul>").appendTo(gridRowHolder);
				  }
				$(this).clone().appendTo($(this).parent().eq(0).siblings("div.gridRowHolder").children("ul:last")[0]);
		});
		$(element).eq(0).remove();	  // remove the original UL
		
		$("ul.gridRow li:last-child").css("margin-right","0");		// gets rid of any right margin on the last item of each row
	}
		makeGridList("ul.items-list", 4);	// 1st argument is a selector for the original UL, the 2nd is the number of columns in the grid
		
		//This is needed to reload gridlist after an item has been added - page is realoded you see. :)
		Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(sender, args) {
			makeGridList("ul.items-list", 4);
			try { tb_init('a.thickbox, area.thickbox, input.thickbox');//pass where to apply thickbox
				}
				
			catch(err){}
			
			 if ($("#personalisation").is(":visible") == true) {
			 $('#personaliseBG').css('display', 'block')
			 
			 if ( $.browser.msie && /6.0/.test(navigator.userAgent) ){
					
					$('#personaliseBG').css('position', 'absolute');
					$('#container').css('position', 'static');
					$('body','html').css({height: '100%', width: '100%'}); 
					$("html").css('overflow','hidden');
					$('#personaliseBG').css('width', $(window).width());
					$('#personaliseBG').css('height', $(window).height());
					$("#personalisation").css('left', ($(window).width() / 2) - 420);
						if ($.fn.bgiframe){
							$('#personalisation').bgiframe();
						}
					}	
			 }
			 else {
			 $('#personaliseBG').css('display', 'none')
			 if ( $.browser.msie && /6.0/.test(navigator.userAgent) ){
			 $('#container').css('position', 'relative')
			 }
			 }

		})
});



//for "edit delivery address" slider on the delivery page checkout
$(document).ready(function(){
    new Expandable($("#edit-delivery"));
});

function Expandable(rootElement) { // general purpose expand down/up element behaviour
  var expandable = this;
  var container = $('.container', rootElement);
  var containerFinalHeight = "" + container.height() + "px";
  var titlebar = $('.titlebar', rootElement);
  var closeButton = $('<span />').text('x');
  var isExpanded = false;
  
  $(titlebar).append(closeButton);
  $(closeButton).hide();  
 

  $(container).css({ // setup for future animation
    height: '0px', 
    overflow: "hidden"
  });

  
  $(titlebar).click(function() {
    if ( isExpanded ) {
      expandable.contract();
    } else {
      expandable.expand();
    }
  })
  
  this.expand = function() {
    $('.container', rootElement).animate({
      height: containerFinalHeight
    });
    $(closeButton).show();
    $(rootElement).addClass('expanded');
    isExpanded = true;
  }
  
  this.contract = function() {
    $(container).animate({
      height: '0'
    });
    $(closeButton).hide();
    $(rootElement).removeClass('expanded');
    isExpanded = false;
  }

  return this;
}

// this is for the delivery date picker for the cut off date delivery preferece
jQuery(function() {
    $('input.textfield.date').each(function() {
        var minDate = $.datepicker.parseDate('dd/m/yy', $(this).val());
        $(this).datepicker({ 
            dateFormat: 'dd/mm/yy',
            minDate: minDate,
            maxDate: '+50',
            hideIfNoPrevNext: true,
            beforeShowDay: function(date) {
                if ( $.datepicker.formatDate('DD', date) == 'Sunday' ) {
                    return [false, ""];
                } else {
                    return [true, ""];
                }
            },
            onClose: function(date) {
                if (date) {
                    $('input[id$=UpdateRequiredDeliveryDate]').click();
                }
            }
            
        });
    });
});

//Close personalisation overlay
jQuery(function() {
	Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(pageLoadedHandler);
	
	// UPDATE PANELS start here
	function pageLoadedHandler(sender, args) {
		closeOverlay();
	
	} //end updatepanels
});


function closeOverlay() {
	$('a.close').click(function() {
		$('#personalisation').css('display', 'none');
		$('#personaliseBG').css('display', 'none')
		
		if ( $.browser.msie && /6.0/.test(navigator.userAgent) ){
			$('body','html').css({height: 'auto', width: 'auto'});
			$("html").css('overflow','auto');
			$('#container').css('position', 'relative')
		}
	});
};




