﻿/*
Edited: 30 June 2009 (Laura Zucchetti @ 17:48)
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');
    }
});


// 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/hawkinsBazaar/scripts/jquery.bgiframe.min.js");
	}
}); 

// FIX PNG24 images in IE6
$(function() { 
    Sys.WebForms.PageRequestManager.getInstance().add_pageLoaded(function(sender, args) { // do this on page load and after an update panel
        if (jQuery.fn.supersleight) { // not required if supersleigh isn't loaded
            $('img').supersleight({
                shim: "/Assets/HawkinsBazaar/images/transparent.gif" 
            });

            $('.product .add input.button').each(function() { // add buttons are inputs, which don't work with supersleight. Using GIF instead.
                this.src = this.src.replace(/png$/i, 'gif');
            });
			
			 $('#footer .newsletter input.button').each(function() { // add buttons are inputs, which don't work with supersleight. Using GIF instead.
                $(this).attr("src", "/Assets/HawkinsBazaar/images/btn-go-footer.gif");
            }); 
			
			$('#col1 .newsletter input.button').each(function() { // add buttons are inputs, which don't work with supersleight. Using GIF instead.
                $(this).attr("src", "/Assets/HawkinsBazaar/images/btn-go-newsletter.gif");
            });

        };
    });
    
});





$(document).ready(function(){
	// this is for the more section of primary nav
	/*$("li.more>a").click(function () {
		$("#more-submenu").toggle();
	});*/
	
    // invoking the carousel
if ($('#frontpageproducts.carousel ul').length > 0) {
             var prevBtn = '<div class="prev"></div>';
             var nextBtn = '<div class="next"></div>';
             
             var secs = 1000;
             $('#frontpageproducts.carousel').wrap('<div class="carousel-outer"/>').before(prevBtn).after(nextBtn);
             $('.carousel-outer').show("slow");
             $('#frontpageproducts.carousel').css('display', 'block');
             $('#frontpageproducts.carousel').jCarouselLite({
                 btnNext: "div.next",
                 btnPrev: "div.prev",
                 visible: 5,
                 scroll: 5,
                 auto: 40*secs,
                 speed: 1.5*secs
             });
         };
        
    // this is for top-nav
    $('#site-navigation ul.catagories > li').each(function() {
        $(this).hover(function() {
            var newClassName = this.className + "-active"; // using ugly class names for IE6 support
            $(this).data('oldClassName', this.className);
            
            $(this).addClass(newClassName + ' active');
            
            if ($.fn.bgiframe) {
                $(this).children('ul').bgiframe();
            };
        }, function() {
            $(this).attr( 'class', $(this).data('oldClassName') );
        });
    });
    
    // dynamic shadows!!
    function titleShadows(titleType) {
         if ( $.browser.safari ) {
             $(titleType).addClass("safari")
             }
         else if ( $.browser.msie ) {
             $(titleType).addClass("msie");
             $(titleType).wrap(document.createElement("div")).parents('div').addClass("msie");
             }
         else if ( '$.browser.mozilla' || '$.browser.opera') {
             $(titleType).addClass("firefox");
             $(titleType).wrap("<div></div>").parent('div').addClass("firefox");
             $(titleType).each(function() {
                 var beforeText = $(this).text()
                 $(this).before("<strong>" + beforeText + "</strong>");
                 });
             }
         else {  
             }
     }
    
    // end shadows
    //
    // invoking the shadows for category links
    if ($('.cat-links').length > 0) {
     titleShadows('.cat-links h3');
    }
    if ($('.cat-head').length > 0) {
     titleShadows('.cat-head h1');
     titleShadows('.cat-head h3');
    }
    // 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

     // changing all the list elements to select elements
     $(list).each( function () {
         var newSelect = $("<select>");
         $(this).find('a').each( function () {
             var linkValue = $(this).attr('href');
             var nameValue = $.trim( $(this).text());
             var newOption = $("<option value='' />").text(nameValue).val(linkValue + ' ');
             // $(this).replaceWith(newOption);
             $(newOption).appendTo(newSelect);
         });
         $(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 .sort-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"});
         }); 
     };
    
     activeOptions('.paging');
     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
     
     $(element).children("li:last-child").css("margin-right","0");       // gets rid of any right margin on the last item of each row
        $('.gridRowHolder ul:last-child').addClass('last');
 }

     makeGridList("ul.items-list", 4);   // 1st argument is a selector for the original UL, the 2nd is the number of columns in the grid
    makeGridList(".whats-new ul", 4);
     //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);

        });

});



//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();
                }
            }
            
        });
    });
});

$(function() { 
    var fixPNGButtons = function(elm, regex, replacement) { 
        // IE6 uses GIF for the button, so swap it for the hover stage image
        
        if (!$.browser.msie || $.browser.version > 6) { // only proceed for IE6
            return; 
        };
        
        $(elm).find('input.button[src$="gif"]').each(function() { 
            this.src = this.src.toString().replace(regex, replacement);
        });
    }
    
    
    $('#category-list').click(function(e) { // product list hover and click 
        if ($(e.target).is('input') === false ) { 
            var prodAnchor = $(e.target).parents('li.product').eq(0).find('a:first'); 
            window.location = $(prodAnchor).attr('href');
        };
    }).find('li.product').hover(function() {
        $(this).addClass('hover');

        fixPNGButtons(this, /\.gif$/i, '-hover.gif'); // fix PNG24 buttons in IE6

    }, function() {
        $(this).removeClass('hover');
        
        fixPNGButtons(this, /-hover/, ''); // return buttons to default state for IE6 by removing '-hover'
    });
    
    $('#slideshowcontainer').each(function() {
       $(this). slideshow({
            slideDelay: 7000,
            fadeSpeed: 1500
        }).find('div:first').show(); 
    });
    
    $('.list-stores > li').click(function(e) { // store locator search results hover and click
        if ($(e.target).attr('href') != '#') { // ignore links for controlling the Google Map

            window.location = $(this).find('a').eq(0).attr('href');
        };
    }).hover(function() {
        $(this).addClass('hover');
    }, function() {
        $(this).removeClass('hover');
    });
});

$(function() {
   $('input.sv-watermark').each(function() {
      $(this).focus(function() {
         $(this).attr('value', '');
      });
   });
   
   
   $('.newsletter .alert').each(function() {
       var alert = this;
        $('<input>').attr({
            type: 'button',
            value: 'x', 
            'class': 'close',
            alt: 'Close'
        }).click(function() {
            $(alert).fadeOut('fast');
        }).appendTo(alert);
   });
});