/* Javascript stylesheet */
document.write("<link rel=\"StyleSheet\" href=\"/catnicAssets/css/catnicJS.css\" type=\"text/css\" media=\"screen\" />");

/* Jquery */
$(document).ready(function() {
    initialiseSelectBoxes();
	addTabbedContent();	
	advancedSearchEvents();
	addSortEvents();
	clearDefaultSearchText("quicksearchtext");
	attachPaginationEvents();
	initLightBox();
	fnInitAutoScroll(); // homepage scrolling fbs
});

/********************************************************************************
 
Name:     Flash plugin detect
 
*********************************************************************************/
var flashdetect = false;
function fnFlashDetect() {
 if (navigator.plugins && navigator.plugins.length) {
  for (x=0; x < navigator.plugins.length; x++) {
   if (navigator.plugins[x].name.indexOf('Shockwave Flash') != -1) {
     flashdetect = true;      
    break;
   }
  }
 }
 else if (window.ActiveXObject) {
  for (x = 2; x <= 20; x++) {
   try {
    oFlash = eval("new ActiveXObject('ShockwaveFlash.ShockwaveFlash." + x + "');");
    if(oFlash) {
     flashdetect = true;  
    }
   }
   catch(e) {}
  }
 }
}
fnFlashDetect(); // run on file load; 



	
/********************************************************************************
 
Name:     Flash embed
Description:  Writeout flash code. Fixes Eolas update for IE as well.
@param swf  String path to swf file
@param width     Number value of movie width
@param height    Number value of movie height
@param alternateContent String of HTML to be served if flash is not installed
 
*********************************************************************************/
 
flash = new Object();
flash.insert = function(swf,width,height,alternateContent) {
	swf = swf.replace(/\./g,"%2E"); // encode periods as %2e	
 if(flashdetect) {
 flashObject = '<embed src="'+swf+'" menu="false" quality="high" width="'+width+'px" height="'+height+'px" type="application/x-shockwave-flash" salign="T" pluginspage="http://www.macromedia.com/go/getflashplayer" />';
 document.getElementById("noFlashContent").style.display = "none";
 document.getElementById("flashContent").style.display = "block";
 } else {
  document.getElementById("noFlashContent").style.display = "none";
  document.getElementById("flashContent").style.display = "block";
 }
 document.write(flashObject); 
};
 	
/********************************************************************************

Name:     fnPopup
Description: Standard popup, but takes target from href on link.  Scrollbars are 
hidden unless screen resolution is less than 1024 x 768, when scrollbars are present.
 
*********************************************************************************/

function fnPopup(targ, w, h) {
	var width = 450;
	var height = 425;
	var obj = targ.href;
	var sScreenX = screen.width;
	var sScreenY = screen.height;
	var x = sScreenX - width;
	var y = sScreenY - height;
	var winLeft = x/2;
	var winTop =  y/2;	
	var scrollStatus = "no";
	
	 if (typeof w == "undefined") {
  	 //
  	}else{
  		width = w;
  		}
  	
  	 if (typeof h == "undefined") {
  	 //
  	}else{
  		height = h;
  		}
  	
	


	window.open(obj,"","width=" + width + ",height="+ height + ",scrollbars=" + scrollStatus + ",left=" + winLeft + ",top=" + winTop + ",resizable=yes, status=no");
	
	return false;
}	

/********************************************************************************

Name:           validate_postcode
Description:    validates the postcode in the stockist search feature block
Return:         true if a postcode has been entered, otherwise false
 
*********************************************************************************/

function validate_postcode(field,errorText,location)
{
    with (field)
    {
        if (field.value==null||field.value=="")
        { 
                document.getElementById(location + "parPostcodeValidation").innerHTML = errorText; 
                return false;
        }
        else 
        { 
            document.getElementById(location + "parPostcodeValidation").innerHTML = ""; 
            return true; 
        }
    }
}

/********************************************************************************

Name:           validate_productType
Description:    validates the product type in the stockist search feature block
Returns:        true if the product type has been changed
 
*********************************************************************************/

function validate_productType(field, errorText,location)
{
    with (field)
    {
        if (field.value==-1)
        {
                document.getElementById(location + "parProductTypeValidation").innerHTML = errorText; 
                return false; 
            }
        else
            {
                document.getElementById(location + "parProductTypeValidation").innerHTML = ""; 
                return true; 
            }
    }
}

/********************************************************************************

Name:           validate_productType
Description:    validates the stockist search feature block by calling
                validate_productType and validate_postcode
Returns:        true if the form validates, otherwise false
 
*********************************************************************************/

function validate_search(thisform, location)
{
    if (location == "fb")
    {
        location = "StoreLocatorFB1_";
    }
    else if (location == "search")
    {
        location = "StoreLocator1_"
    }

    with (thisform)
    {
        var bIsValid = true;  
        if (validate_productType(document.getElementById(location + "ddProductType"),"Please select a product type", location)==false)
        {
            document.getElementById(location + "ddProductType").focus();
            bIsValid = false;
        }      
        if (validate_postcode(document.getElementById(location + "txtPostCode"),"Please enter your postcode", location)==false) 
        {
            document.getElementById(location + "txtPostCode").focus();
            bIsValid = false;
        }
        return bIsValid;
    }
}

function validate_email(thisEmail){

   var sMsg = ""   
   var sEmail = thisEmail.value;
   if(sEmail.indexOf("@") <= 0 || sEmail.indexOf(".") <= 0){
      sMsg = sMsg + "Invalid email address.\n";
      alert(sMsg)
   }

}

// check to see if input is alphanumeric
function validate_telephone(thisTel) {
   var sMsg = ""  
   var sTel = thisTel.value; 
   if (sTel.match(/^[0-9\+\(\.\ \)]+$/)) {
      //return true;
   } else {
      sMsg = sMsg + "Invalid telephone number.\n";
      alert(sMsg)
   } 
}

function addTabbedContent() {
	$(".tabbedGroup").each(function(i) {
		$(this).attr("id","tabbedGroup"+i);		
		$(this).before('<ul class="tabs cfx" id="tabs'+i+'"></ul>');
		if($(".tabbedContent.selected",this).size()>0) { // show a specific tab
			$(".tabbedContent:not(.selected)",this).hide();
			var selectedIndex = $(".tabbedContent",this).index($(".tabbedContent.selected",this));
		} else { // Show tab 1
			$(".tabbedContent:gt(0)",this).hide();
			var selectedIndex = 0;
		}		
		$(".tabbedContent h2",this).each(function(j){
			var sel = j==selectedIndex ? ' class="selected"' : '';
			$("#tabs"+i).append("<li><a href=\"#"+$(this).parent().attr("id")+"\""+sel+">" + $(this).text() + "</a></li>");
		});		
	})
	tabClickEvents();
}
function tabClickEvents() {
	$(".tabs a").click(function(){
		var groupID = $(this).parent().parent().attr("id").toString().split("tabs")[1];
		$("#tabs"+groupID+" a").removeClass("selected");
		$("#tabbedGroup"+groupID+" .tabbedContent").hide();
		$(this).addClass("selected");
		$("#"+$(this).attr("href").toString().split("#")[1]).show()
		return false
	})
}

/* Quick search */
function clearDefaultSearchText(id) {
	$("#"+id).unbind("focus,blur").focus(function () {		
		if ($(this).val() == $(this)[0].defaultValue) {
	    	$(this).val("");
	    }
	 }).blur(function() {
	    if ($(this).val() == "") {
	    	$(this).val($(this)[0].defaultValue);
	 	}
	 });
}

function initialiseSelectBoxes() {
    
    $("#outerleafWrp select").attr("disabled", true);
    $("#cavityWrp select").attr("disabled", true);
    $("#innerleafWrp select").attr("disabled", true);
    $("#wallwidthWrp select").attr("disabled", true);
    
   
	switch( $("#wallconstructionWrp select").val()) {
		case "1":
			$("#outerleafWrp select, #cavityWrp select, #innerleafWrp select, #loadingWrp select").removeAttr("disabled");
		break;
		case "2":
			$("#cavityWrp select, #innerleafWrp select, #loadingWrp select").removeAttr("disabled");
		break;
		case "3":
			$("#outerleafWrp select, #cavityWrp select, #loadingWrp select").removeAttr("disabled");
		break;
		case "4":
			$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
		break;
		case "5":
			$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
		break;
			case "6":
				$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
			break;
		default:			
		break;    
		}
    
}

/* Advanced search */
function advancedSearchEvents() {
	$("#wallconstructionWrp select").change(function(){
		$("#advancedsearch select:gt(0)").attr("disabled","disabled").removeAttr("selected").find('option:first').attr('selected', 'selected');
		var val = $(this).val();
		switch(val) {
			case "1":
				$("#outerleafWrp select, #cavityWrp select, #innerleafWrp select, #loadingWrp select").removeAttr("disabled");
			break;
			case "2":
				$("#cavityWrp select, #innerleafWrp select, #loadingWrp select").removeAttr("disabled");
			break;
			case "3":
				$("#outerleafWrp select, #cavityWrp select, #loadingWrp select").removeAttr("disabled");
			break;
			case "4":
				$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
			break;
			case "5":
				$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
			break;
				case "6":
					$("#wallwidthWrp select, #loadingWrp select").removeAttr("disabled");
				break;
			default:			
			break;
		}	
		
	})
	$("#advancedsearch select").change(function(){
		updateProductCounter();
	});
	$("#advancedsearch input[type='reset']").click(function() {
		$("#advancedsearch select").removeAttr("selected").find('option:first').attr('selected', 'selected');
		$("#advancedsearch select:gt(0)").attr("disabled","disabled");
		$("#resultsCounter").slideUp().text("")
		return false;
	});
	$("#advancedsearch input[type='submit']").click(function() {		
		productSelector(getSearchParameters())
		return false;
	});
}

/**
 * Enable table sorting
 */
function addSortEvents() {
	$("#productSearchResults th a").click(function(){
		var output = getSearchParameters();
		var pairs = $(this).attr("href").toString().split("?")[1].split("&");		
	    for (i=0; i<pairs.length; i++) {
	        var keyValuePair = pairs[i].split("=");
			output[keyValuePair[0]] = keyValuePair[1];
	    }
		productSelector(output)		
		return false;
	})
}

/**
 * attachPaginationEvents
 */
function attachPaginationEvents() {
	$(".pagination a").click(function() {
		var page = $(this).attr("href").toString().split("page=")[1].split("&")[0];
		var sort = $(this).attr("href").toString().split("sort=")[1].split("&")[0];
		var direction = $(this).attr("href").toString().split("dir=")[1].split("&")[0];
		var output = getSearchParameters();
		output['page'] = page;
		output['sort'] = sort;
		output['dir'] = direction;
		productSelector(output) 
		return false;
	})
}

/**	
 * Get Name/Values of all <select> fields in advanced search and encode as data object
 */
function getSearchParameters() {
	var output = {};
	$("#advancedsearch select").each(function(){
		output[$(this).attr("id")] = $(this).val() ;
	})
	return output;
}

// Fetch and unpack json encoded list of results
function productSelector(searchParameters) {
	var tableHeight = $("#productSearchResults table").height();
	$("#productSearchResults").css({height:tableHeight+"px",backgroundPosition:"50% 100px"});
	$("#productSearchResults table").hide()
	$("#productSearchResults table tr").remove();
	//$.getJSON("getProducts.php?jsonnp=?", searchParameters,function(json){
	$.getJSON("/GetProducts.aspx?jsonnp=?", searchParameters,function(json){
		if(parseInt(json.matches)>0) {
			$("#productSearchResults table").append(json.tableHeaders);
			for (product in json.products) {			
				var html = "";
				html +=	'<tr>';
				html +=	'	<td><a href="'+json.products[product].url+'"><img src="'+json.products[product].image+'" alt="" /></a></td>';
				html +=	'	<td>'+json.products[product].productcode+'</td>';
				html +=	'	<td>'+json.products[product].wallconstruction+'</td>';
				html +=	'	<td>'+json.products[product].outerleaf+'</td>';
				html +=	'	<td>'+json.products[product].cavity+'</td>';
				html +=	'	<td>'+json.products[product].innerleaf+'</td>';
				html +=	'	<td>'+json.products[product].wallwidth+'</td>';
				html +=	'	<td>'+json.products[product].loading+'</td>';
				html +=	'	<td><a href="'+json.products[product].url+'" title="'+json.products[product].productcode+'">View</a></td>';
				html +=	'</tr>';
				$("#productSearchResults table").append(html);			
			}				
		} else {
			$("#productSearchResults table").html('<tr><td>No results</td></tr>');
		}
		var newTableHeight = $("#productSearchResults table").height();
		$("#productSearchResults").css({backgroundPosition:"0 -200px"}).animate({height:newTableHeight+"px"},100)
		$("#productSearchResults table").fadeIn();
		addSortEvents();
		updatePagination(json.page,json.totalpages,json.matches,json.sort,json.direction);		
	})
}

// Build pagination links
function updatePagination(page,totalPages,matches,sort,direction) {
	
	var perPage	= 10;
	page 		= parseInt(page);
	totalPages 	= parseInt(totalPages);
	matches 	= parseInt(matches);
	
	if(totalPages>1) {
		var output = page==1? '' : '<a href="?page='+(page-1)+'&amp;sort='+sort+'&amp;dir='+direction+'">Previous</a> | ';
		for(i=1;i<=totalPages;i++) {		
			if(i==page){
				output += i;
			} else {
				output += "<a href=\"?page="+i+"&amp;sort="+sort+"&amp;dir="+direction+"\">"+i+"</a>";
			}
			if(i<totalPages) {
				output += " | ";
			}
		}
		output += page<totalPages? ' | <a href="?page='+(page+1)+'&amp;sort='+sort+'&amp;dir='+direction+'">Next</a>' : "";

		var paginginfo = "";
		var viewall = "<a href=\"?viewall=true\">View all</a>";
		if(matches < (((page-1)*perPage)+perPage) ) {
				paginginfo = "<span>"+(((page-1)*perPage)+1)+" to "+matches+" of "+matches+" products " + viewall +"</span>" + output;
		}else{
		    paginginfo = "<span>"+(((page-1)*perPage)+1)+" to "+(((page-1)*perPage)+perPage)+" of "+matches+" products " + viewall + "</span>" + output;
		}
		$("#productSearchPagination1").html(paginginfo);		
		$("#productSearchPagination2").html(output);
		attachPaginationEvents();
	} else if(totalPages==1) {
	    if(matches < (((page-1)*perPage)+perPage) ) {
		    $("#productSearchPagination1").html("<span>"+(((page-1)*perPage)+1)+" to "+matches+" of "+matches+" products</span>");
		}else{
		    $("#productSearchPagination1").html("<span>"+(((page-1)*perPage)+1)+" to "+(((page-1)*perPage)+perPage)+" of "+matches+" products</span>");
		}
		$("#productSearchPagination2").html("");
	} else {
		$("#productSearchPagination1,#productSearchPagination2").html("");
	}
	
}

// updateProductCounter
function updateProductCounter() {
	$.getJSON("getProductCount.aspx", getSearchParameters(),function(json){
		$("#resultsCounter").slideUp(500, function() {
			$(this).html("Products available: " + json.count).slideDown()
		})
	})
}


/*
	Initialize lightbox plugin for jquery  
	- splayed bay with return bearings
*/ 
function initLightBox () {
	if($('a[rel=lightbox]').length>0){
		$('a[rel=lightbox]').lightBox({
			imageLoading: '/catnicAssets/images/lightbox-ico-loading.gif',
			imageBtnClose: '/catnicAssets/images/lightbox-btn-close.gif',
			imageBtnPrev: '/catnicAssets/images/lightbox-btn-prev.gif',
			imageBtnNext: '/catnicAssets/images/lightbox-btn-next.gif',
			containerResizeSpeed: 350		// faster is better for poor machines - slower looks slicker
	   });
   }
};


// Inifinite Carousel with Auto scroll
// Modified from http://jqueryfordesigners.com/automatic-infinite-carousel/

(function () {
    $.fn.infiniteCarousel = function () {
        function repeat(str, n) {
            return new Array( n + 1 ).join(str);
        }
        
        return this.each(function () {
            // magic!
            var $wrapper = $('> div', this).css('overflow', 'hidden'),
                $slider = $wrapper.find('> ul').width(9999),
                $items = $slider.find('> li'),
                $single = $items.filter(':first'),
                $controls = $("#controls")
                            
                singleWidth = $single.outerWidth(),
                visible = Math.ceil($wrapper.innerWidth() / singleWidth),
                currentPage = 1,
                pages = Math.ceil($items.length / visible),                
                autoscrolling = true,
                stopped = false; // could be an option passed in
                
            // pad the pages with empty element if required
            if ($items.length % visible != 0) {
                // pad
                $slider.append(repeat('<li class="empty" />', visible - ($items.length % visible)));
                $items = $slider.find('> li');
            }
            
            // create the carousel padding on left and right (cloned)
            $items.filter(':first').before($items.slice(-visible).clone().addClass('cloned'));
            $items.filter(':last').after($items.slice(0, visible).clone().addClass('cloned'));
            $items = $slider.find('> li');
            
            // reset scroll            
            $wrapper.scrollLeft(singleWidth * visible);	
                        
            
            // paging function
            function gotoPage(page) {
                var dir = page < currentPage ? -1 : 1,
                    n = Math.abs(currentPage - page),
                    left = singleWidth * dir * visible * n;
                
                $wrapper.filter(':not(:animated)').animate({
                    scrollLeft : '+=' + left
                }, 500, function () {
                	
                    // if page == last page - then reset position
                    if (page > pages) {
                    	
                        $wrapper.scrollLeft(singleWidth * visible);
                        page = 1;
                    } else if (page == 0) {
                    	
                        page = pages;
                        $wrapper.scrollLeft(singleWidth * visible * pages);
                    }
                    currentPage = page;
                });
            }
            
            // insert the back and forward link
            $controls.prepend('<a href="#" id="pause">Pause auto-rotate</a><a href="#" id="play" style="display:none;">Start auto-rotate</a><ul id="pages"><li><a href="1" class="active">1</a></li><li><a href="2">2</a></li><li><a href="3">3</a></li></ul>');
            
            // bind the back and forward links
            $('a.back', this).click(function () {
                gotoPage(currentPage - 1);
                return false;
            });
            
            $('a.forward', this).click(function () {
                gotoPage(currentPage + 1);
                return false;
            });
            
            // custom events
            // goto - go to a specific page, forward and back 
            $(this).bind('goto', function(event, page) {
                gotoPage(page);                
            });
            
            // next - go to next page (autoscrolling)
            $(this).bind('next', function() {            	            	
                gotoPage(currentPage + 1);
                setActive(currentPage);
            });
            
            // pause - pause autoscrolling
            $(this).bind('pause', function() {            	            	
                $("#pause").hide();
				$("#play").show();
            });
            
            // play - play autoscrolling
            $(this).bind('play', function() {            	            	
                $("#pause").show();
				$("#play").hide();
            });
            
            // mouseover - stop the autoscrolling if user is interacting
            $(this).bind('mouseover', function() {            	            	
                autoscrolling = false;
            }).find('a').bind('focus', function() {            	            	
                autoscrolling = false;
            });
         
            // mouseout - start the autoscrolling when user is finished interacting
            $(this).bind('mouseout', function() {            	            	
                if(!stopped)autoscrolling = true;
            }).find('a').bind('blur', function() {            	            	
                if(!stopped){autoscrolling = true;}
            });
            
            //bind jump to page events to page links
		    $('#pages a')
		    	.click(function() {		    		
		    		//console.log(currentPage);
		    		autoscrolling = false;
		    		//currentPage = $(this).text()-1;
		    		$('#autoScroller').trigger('goto',$(this).text());    	
		    		setActive($(this).text()-1);
		    		 stopped = true;
		    		$('#autoScroller').trigger('pause');  		
		    		return false;
		    	});
		    
		    //bind pause/play links
		    $('#pause').click(function () {
		        autoscrolling = false;
		        stopped = true;
		        $('#autoScroller').trigger('pause');
		        return false;
		    });
		    $('#play').click(function () {    	
		    	autoscrolling = true;
		    	stopped = false;
		    	$('#autoScroller').trigger('next');
		    	$('#autoScroller').trigger('play');
		    	
		        return false;
		    });
            
            // Finally, start autoscrolling if enabled
		    setInterval(function () {
		        if (autoscrolling) {
		            $('#autoScroller').trigger('next');                       
		        }
		    }, 4000); 
		    		    
		    function setActive(pageX) {	
				// 2 = manually set number of pages
				if(pageX > 2){
					pageX=0	;
				}
				$("#pages a")
					.removeClass('active')
					.eq(pageX).addClass('active'); 
			}
		    
		    
        });
    };
})(jQuery);

// Uses infiniteCarousel() plugin defined above
function fnInitAutoScroll() {
	$('#autoScroller').infiniteCarousel();
	
	/*
	
	var autoscrolling = true;
	
    $('#autoScroller').infiniteCarousel().mouseover(function () {
        autoscrolling = false;
    }).mouseout(function () {
        autoscrolling = true;
    });
    
	setInterval(function () {
        if (autoscrolling) {
            $('#autoScroller').trigger('next');                       
        }
    }, 4000);    
    */ 
    /*  
    //bind jump to page events to page links
    $('#pages a')
    	.click(function() {
    		autoscrolling = false;
    		$('#autoScroller').trigger('goto',$(this).text());    	
    		setActive($(this).text()-1);  
    		pause();  		
    		return false;
    	});
    
    //bind pause/play links
    $('#pause').click(function () {
        autoscrolling = false;
        pause();
        return false;
    });
    $('#play').click(function () {    	
    	autoscrolling = true;
    	$('#autoScroller').trigger('next');
    	play();
        return false;
    });
	*/
}
/*
// toggle link buttons
function play() {	
	$("#pause").show();
	$("#play").hide();
}

// toggle link buttons
function pause() {	
	$("#pause").hide();
	$("#play").show();
}

// set the active page indicator (orange dot)
function setActive(page) {	
	// 2 = manually set number of pages
	if(page > 2){
		page=0	;
	}
	$("#pages a")
		.removeClass('active')
		.eq(page).addClass('active'); 
}
*/