///////////////////////////////////////////////////////////////////////////////////
//
//  Shop
//
///////////////////////////////////////////////////////////////////////////////////
//
//function strip_html_tags_and_trim(tags) {
//    var stripped = tags.replace(/\<[^<]+\>/gi, "");
//    var trimmed = stripped.trim();
//    return trimmed;
//}

function getVal() {
    return $(this).val();
}

function withId(id) {
    return function() {
        return $(this).attr('id') == id;
    }
}

function withName(name) {
    return function() {
        return $(this).attr('name') == name;
    }
}

function updateAvailabilityBy(attribute, filteredProducts) {
    return function() {
        var id = $(this).attr('id');
        var greped = $.grep(filteredProducts, function(item) {
            return item[attribute] == id;
        });
        var empty = greped.length == 0;
        $(this).siblings().toggleClass('jqTransformDisabled', empty);
        if (empty) {
            $(this).attr("disabled", "disabled");
        } else {
            $(this).removeAttr("disabled");
        }

    }
}

function applyPredicates(predicates) {
    return function(element) {
        for (var i = 0; i < predicates.length; i++) {
            if (!predicates[i](element)) {
                return false;
            }
        }

        return true;
    }
}

var checkMinPrice = function() {
    return function (product) {
        return parseFloat(product.price) >= minPrice;
    }
};

var checkMaxPrice = function() {
    return function(product) {
        return parseFloat(product.price) <= maxPrice;
    }
};

var checkCategory = function() {
    var categories = $("input[name='catSelect']:checked").map(getVal).get();
    return function(product) {
        return $.inArray(product.category, categories) !== -1;
    }
};

var checkBrand = function() {
    var brands = $("input[name='brandSelect']:checked").map(getVal).get();
    return function(product) {
        return $.inArray(product.brand, brands) !== -1;
    }
};


//disable checks
$("input").filter(withName("catSelect")).attr("disabled", "disabled").parent().hide();
$("input").filter(withName("brandSelect")).attr("disabled", "disabled").parent().hide();


// start user setings
var maxColumn = 3; // max cells in a row  
var range = 20; // range of num links to show
// end user setings

var rowsPerPage = 6;
var currentpage = 0;
var maxPrice = null;
var minPrice = null;
var sortBy = 'title';
var sortOrder = 0;

var products = [];

$(".shop-product-small").each(function () {
    var item = {};
    var lis = $(this).find("div");
    item.image = lis.get(0).innerHTML;
    item.title = lis.get(1).innerHTML;
    item.sale = lis.get(2).innerHTML;
    item.view = lis.get(3).innerHTML;
    item.price = lis.get(4).innerHTML;
    item.category = lis.get(5).innerHTML;
    item.brand = lis.get(6).innerHTML;
    item.status = lis.get(7).innerHTML;

  //	item.title = strip_html_tags_and_trim(item.title);
//	item.category = strip_html_tags_and_trim(item.category);
//	item.brand = strip_html_tags_and_trim(item.brand);
 


    var price = parseFloat(item.price);
    if (maxPrice == null || maxPrice < price) {
        maxPrice = price;
    }
    if (minPrice == null || minPrice > price) {
        minPrice = price;
    }


    products.push(item);

    //console.log(products);

    //enable checks
    $("input").filter(withId(item.category))
            .removeAttr("disabled").attr("checked", true).parent().show();

    $("input").filter(withId(item.brand))
            .removeAttr("disabled").attr("checked", true).parent().show();

});


function setProducts(attributeChanged) {
    rowsPerPage = rowsPerPage ? rowsPerPage : $('.product_pages button:first').html();
    var desc = sortOrder > 0;
    currentpage = currentpage > 0 ? currentpage : 1; // if current page is less than first page...
    var totalLoop = rowsPerPage;
    var loop = 0;
    var countCellData = 0;
    var offset = 0;
    // empty content  
    $('#product_show').html('&nbsp;');


    var filteredProducts = [];
    var filteredByPrice = [];
    var filteredByPriceAndDesigner = [];

    if (!minPrice && !maxPrice) {
        filteredProducts = filteredByPrice = filteredByPriceAndDesigner = products;
    } else {
        filteredProducts = $.grep(products, applyPredicates([checkMinPrice(), checkMaxPrice(), checkCategory(), checkBrand()]));
        filteredByPrice = $.grep(products, applyPredicates([checkMinPrice(), checkMaxPrice()]));
        filteredByPriceAndDesigner = $.grep(products, applyPredicates([checkMinPrice(), checkMaxPrice(), checkBrand()]));
    }

    //console.log($("input[name='colorSelect']:checked"));
    //console.log(filterdProducts);

    // get the amount of results
    var totalResults = filteredProducts.length;
    if (totalResults > 0) {
        // if there are results - set selected order
        filteredProducts.sort(function (a, b) {
            var a1 = a[sortBy],
                    b1 = b[sortBy];
            //var a1= a[sortColour], b1= b[sortColour];
            if (a1 == b1) {
                return 0;
            }
            if (desc) {
                return (a1 > b1) ? -1 : (a1 < b1) ? 1 : 0;
            } else {
                return a1 > b1 ? 1 : -1;
            }
        });
    }

    if (attributeChanged == "price") {
        $("input").filter(withName("brandSelect")).each(updateAvailabilityBy("brand", filteredByPrice));
        $("input").filter(withName("catSelect")).each(updateAvailabilityBy("category", filteredByPriceAndDesigner));
    } else if (attributeChanged == "brand") {
        $("input").filter(withName("catSelect")).each(updateAvailabilityBy("category", filteredByPriceAndDesigner));
    }


    // show the amount of results
    $('.product_results').html(totalResults);
    /****** start buil*/
    var totalpages = Math.ceil(totalResults / rowsPerPage);
    // calculate the total pages 
    if (totalpages > 1) {
        // fix displayed page number if its biger then exist
        if (currentpage > totalpages) {
            // set current page to last page
            currentpage = totalpages;
        }
        // set the offset of the list, based on current page 
        offset = (currentpage - 1) * rowsPerPage;

        var pagebtns = '';
        var pagination = '';
        var lastPage = 0;
        // set the min page of the list, based on the range 
        var minPage = parseFloat(currentpage) - parseFloat(range);
        minPage = minPage > 0 ? minPage : 1;
        // if not page 1, don't show back links
        if (currentpage > 1) {
            // get previous page num  
            pagebtns += '<div class="productsearchPrevious"><a id="' + (currentpage - 1) + '" class="product_button prev">Back<\/a><\/div>';
            // show page 1 only if the min page isn`t page 1 (prevent page 1 to show twice)  
            if (minPage > 1) {
                pagination += '<a id="1" class="product_button">1<\/a>';
            }
        }

        // loop to show links to range of pages around current page
        for (var x = minPage; x <= (currentpage + range); x++) {
            // validate page number 
            if (x <= totalpages) {
                lastPage = x;
                // if this is current page set its value to 0 (prevent click) and set class as selected
                if (x == currentpage) {

                    //   <div class="pagination">

                    pagination += '<div class="pagination"><a id="0" class="product_button_selected activ" title="' + x + '" > / ' + x + '<\/a><\/div>';
                } else {
                    pagination += '<div class="pagination"><a id="' + x + '" class="product_button" title="' + x + '" > / ' + x + '<\/a><\/div>';
                }
            }
        }

        // if not on last page, show forward and last page links        
        if (currentpage != totalpages) {
            // get next page 
            var nextPage = parseFloat(currentpage) + 1;
            if (lastPage < totalpages) {
                // show page last page only if the min page isn`t last page (prevent page 1 to show twice)  
                pagination += '<a="' + totalpages + '" class="product_button" title="' + totalpages + '" >' + totalpages + '<\/a>';
            }

            pagebtns += '<div class="productsearchNext"><a id="' + nextPage + '" class="product_button next">Next<\/a><\/div>';
            //pagination += ' <div class="productsearchNext"><a href="#" name="'+nextPage+'">Next</a></div>';  

        }
        // update the html
        $('.product_pagebtns').html(pagebtns);
        $('.product_pagination').html(pagination);
    } else {
        // if no pages or just one page dont show pagination
        $('.product_pagination').html('<div class="pagination"><a id="0" class="product_button_selected" title="1" >/ 1<\/a><\/div>');
    }
    var offsetEnd = parseFloat(rowsPerPage) + parseFloat(offset);
    /****** end buil*/

    // build cells content
    var cell = '<div id="product_table">';

    // get the keys is in the display pagination range
    var pageProducts = filteredProducts.slice(offset, offsetEnd);
    // loop over the query list 
    $.each(pageProducts, function (i, object) {
        // get min and max price range for price range filter slider   
        setPriceRange(parseFloat(object.price));
        countCellData++; // flug to know if there is content                
        cell += '<div class="shop-product-small clear">';


        cell += '<div class="onSaleTag"></div>';
        cell += '<div class="image">' + object.image + '<\/div>';
        cell += '<div class="title">' + object.title + '<\/div>';
        cell += '<div class="price">' + object.sale + '<\/div>';
        //cell += '<div class="view">' + object.view + '<\/div>';
        cell += '<div class="status">' + object.status + '<\/div>';


        cell += '<\/div>';


        totalLoop--;
        loop++;

        //if on sale
        var sale = $(".onSaleObject").html();
        if (sale > 0) {
            $(".onSaleTag").fadeIn("slow");
        } else {
            $(".onSaleTag").hide();
        }

        // if the row ended but the table as unmach cells  number
        if (!totalLoop && loop) {
            for (var i = 0; i < (maxColumn - loop); i++) {
                // add empty cell     
                cell += '<div>&nbsp;<\/div>';
            }
        }
        // determine if the row ended  
        if (loop == maxColumn) {
            cell += '<\/div>';
            loop = 0;
            if (totalLoop) {
                cell += '<div>';
            }
        }
    });
    cell += '<\/div>';
    if (countCellData > 0) {
        // if exist content
        $('#product_show').html(cell);
        // set image onclick event
        //   $('#product_show img').click(function(){ 
        //  alert('Product ID = '+$(this).attr('longdesc'));
        // });
    }
    setPagination();
}


function setPriceRange(price) {
    // find min and max price range   
    if (maxPrice < price) {
        maxPrice = price;
    }
    if (minPrice > price) {
        minPrice = price;
    }
}


// price range animation slider
function PriceRangeSlider() {
    $("#product_price_slider").slider({
        range: true,
        min: 1,
        max: maxPrice,
        values: [minPrice, maxPrice],
        slide: function (event, ui) {
            // update the html for the slider value
            $("#product_price_range_min").html("£" + ui.values[0]);
            $("#product_price_range_max").html("£" + ui.values[1]);
        },
        stop: function (event, ui) {
            // update query on price range
            currentpage = 0;
            minPrice = ui.values[0];
            maxPrice = ui.values[1];
            displayProducts("price");


        }
    });
    // update the html for the slider value before its changes  
    $("#product_price_range_min").html("£" + $("#product_price_slider").slider("values", 0));
    $("#product_price_range_max").html("£" + $("#product_price_slider").slider("values", 1));

}


// page button click
function setPagination() {
    $('.product_pagination a[id!=0]').click(function () {
        currentpage = $(this).attr('id');
        displayProducts();
    });
    $('.product_pagebtns a[id!=0]').click(function () {
        currentpage = $(this).attr('id');
        displayProducts();
    });
}

// animante list display
function displayProducts(attributeChanged) {

    $('#product_show').fadeOut(100, function () {
        // Animation complete
        setProducts(attributeChanged);
        $('#product_show').fadeIn(100);

        //shop fade
        $(".shop-product-small").hover(function () {
            $(".shop-product-small").stop().animate({
                opacity: 0.3
            }, 200);
            $(this).stop().animate({
                opacity: 1
            }, 200);
            //$(".toolTip", this).fadeIn(300);

        }, function () {
            $(this).css({
                opacity: 1
            });
            $(".shop-product-small").stop().animate({
                opacity: 1
            }, 200);
            //$(".toolTip", this).hide();
        });


        $(".shop-product-small .status").each(function () {

            var stat = $(this).html();

            if (stat == "sale") {
                $(this).css('backgroundPosition', '0 0px').fadeIn(300);
            }
            if (stat == "hot") {
                $(this).css('backgroundPosition', '0 -74px').fadeIn(300);
            }
            if (stat == "new") {
                $(this).css('backgroundPosition', '0 -148px').fadeIn(300);
            }

        });


    });
}


$(document).ready(function () {
    setProducts();
    PriceRangeSlider();
    $("input[name='catSelect']").change(function () {
        currentpage = 0;
        displayProducts("category");
    });

    // $("input[name='sizeSelect']").change(function(){ 
    //        	currentpage = 0; 
    //            displayProducts(); 
    //     })

    $("input[name='brandSelect']").change(function () {
        currentpage = 0;
        displayProducts("brand");
    });

});


///////////////////////////////////////////////////////////////////////////////////
//
//  Framework
//
///////////////////////////////////////////////////////////////////////////////////
function dynamicMenuSelectPersist(url,navID){
     if(window.location.href.indexOf(url) != -1){
          jQuery("#"+navID).addClass("selected");
     }
}



jQuery(function (jQuery) {

    var Engine = {
        utils: {

            //alert
            alertMessage: function () {
                window.alert = function (message) {
                    $('#messageBox').text(message).fadeIn().delay(4000).fadeOut('slow');
                }


            },

            //validate form
            validate: function () {
                $('#signin').validate();
                $('#register').validate();
				$('#newsletter').validate();
				
				$('#newsletter').submit(function(e){
       		 e.preventDefault();
        	$.ajax({
            type: 'POST',
            url: $(this).attr('action'),
            data: $(this).serialize(), 
            success: function (msg) { 		
                $('.success').slideDown();
				$('.link').hide();
				$('.formNews').hide();
				$('#newsletter')[0].reset();
            },
            error: function (msg) {
                 //$('.senderror').slideDown();
				 //$('.success').hide();
            }
       		});		
    		});
			
			
            },
			
			
			navSelectedState : function(nav) { // adds selected state to dynamic menus
                 // pass in the container tag eg 'nav'
                 jQuery(nav + " ul li").each(function(){
                       if (jQuery(this).find("a").attr('href') === window.location.pathname)
                       {
                             jQuery(this).addClass('selected');
                             jQuery(this).parents("li").addClass('selected');
                       }   
                 });
            },// navSelectedState
            
            webAppNavPersist : function(){ // pass url and ID of li
                 //dynamicMenuSelectPersist("just-in","main-nav-just-in");
                 dynamicMenuSelectPersist("best-sellers","main-nav-best-sellers");
				 dynamicMenuSelectPersist("just-in","main-nav-justin");
				 dynamicMenuSelectPersist("road-bikes","main-nav-road");
				 dynamicMenuSelectPersist("mountain","main-nav-mountain");
				 dynamicMenuSelectPersist("components","main-nav-components");
				 dynamicMenuSelectPersist("accessories","main-nav-accessories");
				 dynamicMenuSelectPersist("find-us","main-nav-find");
            } // webAppNavPersist
			
			
			
        },
        ui: {

            //cartsummary
            cartSummary: function () {
                var cart = $(".cartSummaryItem").html()
                if (cart == "Shopping cart is empty.") {
                    $(".cartSummary").hide();
                } else {
                    $(".cartSummary").show();
                }

			
			
			$("#addCart").click(function(){
				var a=$(".cartSummaryItem").html();
				if(a=="Shopping cart is empty."){
					$(".cartSummary").hide()
					}else{
						$(".cartSummary").fadeIn(500)}
				});
			
			
			
            },
            //end

            //thumb fade
            thumbFade: function () {
                $(window).load(function () {
                    $(".shop-product-small").hover(function () {
                        $(".shop-product-small").stop().animate({
                            opacity: 0.3
                        }, 500);
                        $(this).stop().animate({
                            opacity: 1
                        }, 500);
                        $(".toolTip", this).fadeIn(300);

                    }, function () {
                        $(this).css({
                            opacity: 1
                        });
                        $(".shop-product-small").stop().animate({
                            opacity: 1
                        }, 500);
                        $(".toolTip", this).hide();
                    });
					
			
				
                });

            },
            //end

           
            //panel
            panel: function () {
                $(".panelBtn, .panelOpen").click(function () {
                    $("#boxContainer").slideToggle("slow");
                    $(this).toggleClass("active");

                    if ($(this).is('.active')) {
                        $(".panelBtn").html("Close");
                    } else {
                        $(".panelBtn").html("Information Centre");
                    }
                    return false;
                });
				
				
			var active_color = '#e71f2f'; // Colour of user provided text
			var inactive_color = '#363636'; // Colour of default text


			$(document).ready(function() {
  				$(".search input").css("color", inactive_color);
  				var default_values = new Array();
  				$(".search input").focus(function() {
    			if (!default_values[this.id]) {
      				default_values[this.id] = this.value;
    			}
    			if (this.value == default_values[this.id]) {
      				this.value = '';
      				this.style.color = active_color;
    			}
    			$(this).blur(function() {
      			if (this.value == '') {
        			this.style.color = inactive_color;
        			this.value = default_values[this.id];
      			}
    			});
  				});
				});

            },
            //end

            //slide
            slide: function () {
              // var totWidth=0;
//				var positions = new Array();
//	
//			$('#slides .slide').each(function(i){
//		
//				positions[i]= totWidth;
//				totWidth += $(this).width();
//	
//			if(!$(this).width())
//			{
//			//alert("Please, fill in width & height for all your images!");
//			return false;
//			}
//		
//			});
//	
//			$('#slides').width(totWidth);
//	
//			$('.mainNav ul li a').click(function(e,keepScroll){
//					$('li.menuItem').removeClass('act').addClass('inact');
//			$(this).parent().addClass('act');
//				var pos = $(this).parent().prevAll('.menuItem').length;
//				$('#slides').stop().animate({marginLeft:-positions[pos]+'px'},450);
//				//e.preventDefault();
//			if(!keepScroll) clearInterval(itvl);
//			});
//	
//			$('.mainNav ul li.menuItem:first').addClass('act').siblings().addClass('inact');
//	
//	 
//			var current=1;
//			function autoAdvance()
//				{
//			if(current==-1) return false;
//			$('.mainNav ul li a').eq(current%$('.mainNav ul li a').length).trigger('click',[true]);	// [true] will be passed as the keepScroll parameter of the click function on line 28
//				current++;
//			}
//			
//			var changeEvery = 5;
//			var itvl = setInterval(function(){autoAdvance()},changeEvery*1000);

			$('#panels .link').click(function() {
				$('#panels .link').hide();
				$('#panels .formNews').fadeIn(300);
				
				return false;
			});

            },
            //end
			
            //discountcode
            discountCode: function () {
                $('input.discountcodeInput').change(function () {
                    var promo = $(".discAmount").html();
                    if (promo == "£0.00") {
                        $(".not-accept").show();
                    } else {
                        $(".not-accept").hide();
                        $(".accept").fadeIn('slow');
                    }
                });

            },
            //end
			
			//scroller
			scroller: function () {
				
			$('#cat-scroll').jcarousel({
   			wrap: 'circular'
   			 });
			$('#brand-scroll').jcarousel({
    		wrap: 'circular'
    		});

			
			
			$(".shop-product-small .status").each(function () {

			var stat = $(this).html();
			if(stat == "") {
				$(this).css('display' ,'none');
			}
			if(stat == "sale") {
				$(this).css('backgroundPosition' ,'0 0px').fadeIn(300);
			}
			if(stat == "hot") {
				$(this).css('backgroundPosition' ,'0 -74px').fadeIn(300);
			}
			if(stat == "new") {
				$(this).css('backgroundPosition' ,'0 -148px').fadeIn(300);
			}
			
			});
			
			
			
			$("#cat-scroll li div.status").each(function () {

			var lis = $(this).html();

			//console.log(lis); //works fine up to here

			if(lis == "New") {
				$(this).css('backgroundPosition' ,'0 -89px');
			}
			if(lis == "Sale") {
				$(this).css('backgroundPosition' ,'0 -178px');
			}

			});//end
			
			
			
			
			
			
			
			
			
		


			//init
			$('#brandWrap').hide();
			$('.brands').css("color","#363636");

			
			$('.categories').click(function() {
				$('#brandWrap').hide();
				$('#catWrap').fadeIn(500);
			
				$('.categories').css("color","#d90718");
				$('.brands').css("color","#363636");
			});
		
			$('.brands').click(function() {
				$('#catWrap').hide();
				$('#brandWrap').fadeIn(500);
				
				$('.brands').css("color","#d90718");
				$('.categories').css("color","#363636");
			});
				
					
			},
			//end
			
			
			
			tweet: function () {
			jQuery(function ($) {
			$(".newsList").tweet({
          	join_text: "auto",
          	username: "ActivCycles",
          	count: 1,
          	auto_join_text_default: "we said,", 
          	auto_join_text_ed: "we",
          	auto_join_text_ing: "we were",
          	auto_join_text_reply: "we replied",
          	auto_join_text_url: "we were checking out",
          	loading_text: "searching twitter...",
        	refresh_interval: 10
			});
        });	
				
			},//end
			
			
			
            //pages
            pages: function () {
				
				//product page
				 if (typeof (productPage) !== 'undefined') {
					var crumbs = $("div.breadcrumbs");
					crumbs.html( crumbs.html().replace(":","/") );
				
					// hide empty cat
					if(jQuery("td.catalogueItemNotFound").text() == "This catalog has no sub-catalogs."){
					   jQuery("td.catalogueItemNotFound").hide();
					
					}
				 }
				
                //on large page
                if (typeof (productDetail) !== 'undefined') {
                 	
					var crumbs = $("div.breadcrumbs");
					crumbs.html( crumbs.html().replace(":","/") );
					
					
                    $("#product_plugin, #filterPanel, .product_pagination").hide();
                    $(".productsList").show();
					
					
			
						
					
					// hide empty cat
					if(jQuery("td.catalogueItemNotFound").text() == "This catalog has no sub-catalogs."){
					   jQuery("td.catalogueItemNotFound").hide();
					}
					
					//brand logos
					if($(".brandTitle").text() == "sandy bay"){
					   $(".brand").css('background-image','url(/images/brands/sandybay.jpg)');
					}  
					if($(".brandTitle").text() == "heyland whittle"){
					   $(".brand").css('background-image','url(/images/brands/heyland-whittle.jpg)');
					}  
					if($(".brandTitle").text() == "orangery"){
					   $(".brand").css('background-image','url(/images/brands/orangery.jpg)');
					}  
					 
                } //end  
				
				
				 
				//on cart page
                if (typeof (productCart) !== 'undefined') {
					$(".cartSummary").hide(); 
                } //end
				
				

            } //end
        }
    };

    Engine.utils.alertMessage();
    Engine.utils.validate();
	Engine.utils.navSelectedState('nav');
    Engine.utils.webAppNavPersist();

    Engine.ui.cartSummary();
    Engine.ui.thumbFade();
    Engine.ui.panel();
    Engine.ui.slide();
	Engine.ui.scroller();
    Engine.ui.discountCode();
    Engine.ui.pages();
	Engine.ui.tweet();


});
