$(Initialise);

var listItems = null;
var thumbItems = null;
var timer = null;

function Initialise() {
    InitialiseSelectMenu();
    InitialiseCufon();
	InitialiseModals();
	
	$('input.watermark,textarea.watermark').watermark();
	
	if($('.hero-panel-images').length > 0) {
		listItems = $('.hero-panel-images').children();
		thumbItems = $('.hero-thumbs').children();
		setHeroImage(1);
	}
	
	$('.banner-buttons-box-inner').bind('mouseleave',function(e){
		animateHero('0');															
	});
	
	
	$('.banner-button').bind('click mouseover',function(e){
		
		if(e.type == "mouseover") {
			e.stopPropagation();
			
			thumbItems.find('img').css('display','none');
			
			var image = $(thumbItems.get(parseInt($(this).html())-1)).find('img');
			image.fadeIn();
			animateHero('-59');
		}
		else if(e.type == "mouseout") {
			
			/*
			if(timer!= null) {
				clearTimeout(timer);	
			}
			
			timer = setTimeout("animateHero('0')",3000);
			*/
		}
		else {
			//thumbItems.find('img').css('display','block');
			//animateHero('-59');
			setHeroImage(parseInt($(this).html()));
			animateHero('0');
		}
														
	});
	
	/*
	$('.hero-thumbs img').bind('click',function(e){
		setHeroImage(parseInt($(this).attr('title')));
		animateHero('0');
	});
	*/
	
}

$(window).load(function () {
    InitialiseNavigation();
});

function InitialiseModals() {
	$('.modal-link a').bind('click',function() {
		loadModals($(this));									   
	});
}

var closedialog;
var currentDialog;

function overlayclickclose() {
	if (closedialog) {
		currentDialog.dialog('close');
	}
	//set to one because click on dialog box sets to zero
	closedialog = 1;
}

function loadModals(object) {
	var content = $(object.parent().siblings('.modal-content'));
	
	currentDialog = $('<div></div>')
		.html(content.html())
		.dialog({
			modal:true,
			resizable:false,
			width:'850',
			open: function(){closedialog = 1;$('.ui-widget-overlay').bind('click', overlayclickclose);},
			focus: function(){closedialog = 0;},
			close: function(){$('.ui-widget-overlay').unbind('click');}
		});
}

function setHeroImage(index) {
	index--;
	removeHeroImages(listItems);
	$(listItems.get(index)).css('display','block');
	
	var content = $(listItems.get(index)).children('.hero-panel-content');
	
	//change text for individual item
	
	$('.product-large-detail').html(getContent('.detail',content));
	//$('.product-large-subtitle').html(getContent('.subtitle',content));
	//$('.product-large-description').html(getContent('.description',content));
	$('.product-large-banner').html(getContent('.banner',content));
	//$('.product-large-price').children('.price').html(getContent('.price',content));
	//$('.product-large-link').attr('href',content.children('.link').html());
}

function getContent(className,content) {
	return content.children(className).html();
}


function removeHeroImages(listItems) {
	listItems.css('display','none');
}

function animateHero(change) {
	$('.hero-panel-inner').animate({
			top: change
			}, 500, function() {
	});	
}

function InitialiseNavigation() {
	
	var counter = 1;
	
    $("#navigation li").each(function () {

        var navContainer = $(this).find('.nav-container');

        if (navContainer.length > 0) {
			
			$(this).addClass('rollout');
			
			var length = $(this).find('.nav-products').find('li').length;

            //calculate widths
            var current = getContainerWidth(navContainer);
			
			var actual = 0;

            //Dont let the product UL have a width wider than 6 products
            if (length < 6) {
                actual = (length * 120) + 140;
            } else {
                actual = (6 * 120) + 140;
            }
			
			//calculate difference and set
            var difference = Math.abs(actual - current) + 25;
			
			navContainer.css('margin-left', '-' + difference + 'px');
           	navContainer.css('min-width', actual + 'px');
			
			counter++;
        }

    });
}

function getContainerWidth(obj) {
	if($.browser.msie && $.browser.version == "7.0") {
		
		//max width of mav bar needs to be found 
		var offset = obj.parent().position().left;
		var newWidth = obj.parent().parent().width() - offset;		
		
		obj.css('max-width',newWidth+'px');
		
		return obj.width();
	
	}
	else if($.browser.msie && $.browser.version == "8.0") {
		
		//max width of mav bar needs to be found 
		var offset = obj.parent().position().left;
		var newWidth = obj.parent().parent().width() - offset - 55;		

		obj.css('max-width',newWidth+'px');
		
		return obj.width();
	
	}
	else {
		return obj.width();	
	}

}

function InitialiseSelectMenu() {
    if($('select').length > 0) {
		$('select').selectmenu({
			style: 'dropdown'
		});
	}
}

function InitialiseCufon() {
    // Only if @font-face is not supported
    if (!IsFontFaceSupported()) {

        // Load Cufon script
        jQuery.getScript("scripts/cufon-yui.js", function () {

            // Load font script
            jQuery.getScript("scripts/TradeGothicBoldCondTwenty_700.font.js", function () {

                // Apply
                Cufon.replace('.Custom-font');

                Cufon.now();
            });
        });
    }
}

function initializeFilters() {
   	var filterElements = jQuery(".filters .result-filter");
	var filterContents = filterElements.find(".filter-selection");
	
   	// Prevent filter items (checkboxes) from bubbling the click event and causing the filter panel to close
    filterContents.bind("click", function (e) {
        e.stopPropagation();
    });

    // Prevent filter items scrollbars from bubbling the click event and causing the filter panel to close
    $('div.filter-scroll').bind("click", function (e) {
        e.stopPropagation();
    });
	
	filterContents.children('li').find('input').bind('click',function(e) {
		
		var allButton = $(this).parentsUntil('div').find('li span.all').children('input');
	
		if($(this).parent().attr('class') != "all") {	
			//check if all is selected
			if(allButton.attr('checked')) {
				turnOffCheckBox(allButton,allButton.parent());
			}
		}
		else {
			//de-select all if all is pressed
			allButton.parentsUntil('div').siblings().each(function() {											  
				turnOffCheckBox($(this).children('input[type=checkbox]'),$(this));
			});
		}
		showFiltered();
		resetPage();
		applyFilters();
	});

    var filtersOpen = false;
    var animating = false;

    filterElements.bind('click', function () {
        var animationSpeed = 300;

        if (!animating) {
            animating = true;

            filterElements.toggleClass('arrowDown arrowUp');

            if (!filtersOpen) {
								/*
                filterElements.animate({ height: 130 }, animationSpeed, function () {
                    filterElements.children('.filter-choice').fadeOut(animationSpeed / 2, function () {
                        filterContents.fadeIn(animationSpeed / 2, function () {
                            animating = false;
                            filtersOpen = true;
                        });
                    });
                });
								*/
								// sequence: hide/setsize/show
								filterElements.children('.filter-choice').hide();
								filterElements.height(140);
								filterContents.show();
								initialiseCheckboxes();
								initialiseFilterScrollbars();
								animating = false;
								filtersOpen = true;
								
								
            } else {
								/*
								filterElements.animate({ height: 29 }, animationSpeed, function () {
                    filterContents.fadeOut(animationSpeed / 2, function () {
                        filterElements.children('.filter-choice').fadeIn(animationSpeed / 2, function () {
                            animating = false;
                            filtersOpen = false;
                        })
                    });
                });
								*/
								filterContents.hide();
								filterElements.height(29);
								filterElements.children('.filter-choice').show();
								animating = false;
								filtersOpen = false;
								//resetPage();
								//applyFilters();
            }
        }
    });
}

function turnOffCheckBox(checkbox,uiObj) {
	uiObj.find('label').removeClass('ui-state-active').attr('aria-pressed',false);
	checkbox.attr('checked', false);
}

function initializeGrid() {
    
    var gridSize = 4;

    var list = jQuery('.catalogue').children('li');
    var maxHeight = 0;
    var limit = 0;

    for (var i = 0; i < list.length; i += gridSize) {
        limit = i + gridSize;
        var group = list.slice(i, limit);

        group.each(function (current) {
            var height = jQuery(group[current]).children('.container').height();
            maxHeight = height > maxHeight ? height : maxHeight;
        });

        group.each(function (current) {
            var currentChild = jQuery(group[current]);
            currentChild.height(maxHeight);

            if ((current % (gridSize - 1) == 0) && current != 0) {
                currentChild.css('marginRight', '0px')
            }

        });

        maxHeight = 0;
    }
}

function initializeSlider() {
    var sliderElement = jQuery(".price");
    var defaultElement = sliderElement.find(".default");

    var minDefault = defaultElement.find(".min .value").text();
    var maxDefault = defaultElement.find(".max .value").text();

    sliderElement.find(".slider").slider({
        range: true,
        min: minDefault,
        max: maxDefault,
        values: [minDefault, maxDefault],
        slide: function (event, result) {
            var amountElement = sliderElement.find(".amount");
            amountElement.find(".min .value")[0].value = result.values[0];
            amountElement.find(".max .value")[0].value = result.values[1];           
        },
        change: function (event,result)
        {
            showFiltered();
            applyFilters();
        }
    });

}


function initialiseFilterScrollbars() {
	$('div.filter-scroll').tinyscrollbar({size:110, sizethumb:'auto'});
}

function initialiseCheckboxes(){
	$('.filter-selection input[type=checkbox]').button().bind('focusin', function(e){
		var $target = $(e.target).closest('.filter-scroll');
		//var x = $(e.target).closest('.filter-scroll .overview').position();
		//$(e.target).closest('.filter-scroll').tinyscrollbar_update(Math.abs(x.top));
		//var el = $target.find('.overview').position();
		//$target.tinyscrollbar_update(Math.abs(el.top));
	});
}

function IsFontFaceSupported() { return Modernizr.fontface;}
function IsCssTransistionsSupported() { return Modernizr.csstransitions; }

function applyFilters()
{

    var lowprice = 0//document.getElementById("lowprice").value;
    var highprice =300// document.getElementById("highprice").value;
    var sliderElement = jQuery(".price");
    var amountElement = sliderElement.find(".amount");
    var objSearchTerm = document.getElementById("SFSearchTerm")
    var objSaleOnly = document.getElementById("saleonly")
    
    if(objSaleOnly != null)
    {
        var saleonly = objSaleOnly.value;
    }
    else
    {
        var saleonly = 0;
    }
    if(objSearchTerm != null) 
    {
        var searchterm = objSearchTerm.value
    }
    else
    {
        var searchterm  = ''
    }
    
    var catID = document.getElementById("categoryID").value
    
//    lowprice = amountElement.find(".min .value")[0].value
//    highprice = amountElement.find(".max .value")[0].value
    
    var crossCat = document.getElementById("CrossCategory")
    var crossCatID = 0
    if (crossCat != null)
    {
        crossCatID = crossCat.value;
    }
    
    
    
    var pgSize = document.getElementById("ItemCountMenu");
    var pgNum = document.getElementById("pgNum").value;
//    var sortBy = document.getElementById("OrderByMenu").options[document.getElementById("OrderByMenu").selectedIndex].value; 
    var SearchType = document.getElementsByName("chkTypeFilter") ;
    var SearchSize = document.getElementsByName("chkSizeFilter") ;
    var SearchColor = document.getElementsByName("chkColourFilter") ;
    var SearchCategory = document.getElementsByName("chkCategoryFilter") ;
    var SearchStory = document.getElementsByName("chkStoriesFilter") ;
    var SearchFeatures = document.getElementsByName("chkFeaturesFilter");
    var SearchStandards = document.getElementsByName("chkStandardsFilter");
    var SearchResistance = document.getElementsByName("chkResistanceFilter");
    
    var typeList = '' ;
    var delim = "";
    for(var i=1;i < SearchType.length;i++)
    {
        if (SearchType[i].checked == true)
        {
            typeList += delim + SearchType[i].value; 
            delim = ",";
        }
    } 
   
   var sizeList = '' ;
   delim = "";
    for(var i=1;i < SearchSize.length;i++)
    {
        if (SearchSize[i].checked == true)
        {
            sizeList += delim + SearchSize[i].value; 
            delim = ",";
        }
    } 
    
    var colorList = '' ;
    delim = "";
    for(var i=1;i < SearchColor.length;i++)
    {
        if (SearchColor[i].checked == true)
        {
            colorList += delim + SearchColor[i].value; 
            delim = ",";
        }
    } 
    
     var categoryList = '' ;
    delim = "";
    for(var i=1;i < SearchCategory.length;i++)
    {
        if (SearchCategory[i].checked == true)
        {
            categoryList += delim + SearchCategory[i].value; 
            delim = ",";
        }
    }
    
     var storyList = '' ;
    delim = "";
    for(var i=1;i < SearchStory.length;i++)
    {
        if (SearchStory[i].checked == true)
        {
            storyList += delim + SearchStory[i].value; 
            delim = ",";
        }
    }
    
    var featureList = '';
    delim = "";
    for(var i=1;i < SearchFeatures.length;i++)
    {
        if (SearchFeatures[i].checked == true)
        {
            featureList += delim + SearchFeatures[i].value; 
            delim = ",";
        }
    }
    
    var standardsList = '';
    delim = "";
    for(var i=1;i < SearchStandards.length;i++)
    {
        if (SearchStandards[i].checked == true)
        {
            standardsList += delim + SearchStandards[i].value; 
            delim = ",";
        }
    }
    
     var resistanceList = '';
    delim = "";
    for(var i=1;i < SearchResistance.length;i++)
    {
        if (SearchResistance[i].checked == true)
        {
            resistanceList += delim + SearchResistance[i].value; 
            delim = ",";
        }
    }
    
    if(pgSize == null)
    {
        var PgItems = 20;
        
    }
    else
    {
            var pgItems = pgSize.options[pgSize.selectedIndex].value;
    }
    
    $.ajax({
    type:'POST',
    url:'x-entity.qsgridwithprices.aspx',
    data:{'catid':catID,'crosscat':crossCatID,'pgsize':pgItems,'pagenum':pgNum,'size':sizeList,'type':typeList,'category':categoryList,'color':colorList,'story':storyList,'SearchTerm':searchterm,'sale':saleonly,'feature':featureList,'standard':standardsList,'resistance':resistanceList},
//    data:{'catid':catID,'crosscat':crossCatID,'pgsize':pgItems,'pagenum':pgNum,'sortby':sortBy,'size':sizeList,'lowprice':lowprice ,'highprice':highprice,'type':typeList,'category':categoryList,'color':colorList,'story':storyList,'SearchTerm':searchterm,'sale':saleonly,'feature':featureList,'standard':standardsList,'resistance':resistanceList},
    dataType:'html',
    success:function(data)
    {
        $('#filtered-items').html(data);
		$('#filtered-items').waitForImages(function() {
           initializeGrid();
        });
        //setTimeout("initializeGrid()",1000);
        
    }
    
    });    
    
}

function applyForLifeFilters()
{

    var lowprice = 0//document.getElementById("lowprice").value;
    var highprice =300// document.getElementById("highprice").value;
    var saleonly = 0;
    
    
    
    
    var catID = document.getElementById("categoryID").value
    
    
    
    var crossCatID = 0
    
    
    
    
    var pgSize = 20
    var pgNum = 1
    var sortBy = 1
    
    
    
    var typeList = '' ;
    
   var sizeList = '' ;
    
    var colorList = '' ;
    
     var categoryList = '' ;
    
     var storyList = '' ;
    
    var featureList = '';
    
    var standardsList = '';
    
     var resistanceList = '';
    var searchterm ='';
    
    
        var pgItems = 9999;
        
    
    
    $.ajax({
    type:'POST',
    url:'x-entity.qsgridwithprices.aspx',
    data:{'catid':catID,'crosscat':crossCatID,'pgsize':pgItems,'pagenum':pgNum,'sortby':sortBy,'size':sizeList,'lowprice':lowprice ,'highprice':highprice,'type':typeList,'category':categoryList,'color':colorList,'story':storyList,'SearchTerm':searchterm,'sale':saleonly,'feature':featureList,'standard':standardsList,'resistance':resistanceList},
    dataType:'html',
    success:function(data)
    {
        $('#filtered-items').html(data);
		$('#filtered-items').waitForImages(function() {
           initializeGrid();
        });
        //setTimeout("initializeGrid()",1000);
        
    }
    
    });    
    
}

function resetPage()
{
document.getElementById("pgNum").value = 1;
}

function showFiltered()
{
    if(document.getElementById("featured-items") != null)
    {
        if(document.getElementById("filtered-items").style.display='none')
        {
            document.getElementById("filtered-items").style.display='';
            document.getElementById("featured-items").style.display='none';
            if(document.getElementById("featured-tab") != null)
			{
				document.getElementById("featured-tab").className = '';
				document.getElementById("filtered-tab").className = 'selected';
			}
        }
    }
    resetFilteredItems();
    
}
function resetFilteredItems()
{
    $('#filtered-items').html('<div style="width:100%;text-align:center;"><img src="images/upload/19-1.gif"/></div>');
}

 function loadRelatedPage(productID, pageNum)
    {
        $.ajax({
    type:'POST',
    url:'x-relatedproducts.aspx?productid=' + productID + '&pagenum=' + pageNum ,
    dataType:'html',
    success:function(data)
    {
        $('#related-content').html(data);
        initializeGrid() ;
        
    }
    
    });
        
    }
