var categoriesJSONUrl = '/api/rest/site/categories/';
var locationsJSONUrl = '/api/rest/site/locations/';
var cartSummaryUrl = '/cartsummary/';//params.cartcachekey;
var cartDetailUrl = '/cart/'
var cartAddItemUrl = '/cart/add/'
var cartDetailJSONUrl = '/cartjson/'
var productTicketsJSONUrl = '/api/rest/product/tickets/'

var cardsPerRow = 4;
var rowsPerPage = 10;		
var maxCards = cardsPerRow*rowsPerPage;
maxCards = 100;
var pg = 1;					// Not implemented
var sortCol = 'random'; 	// Not implemented
var sortOrder = 'ASC';		// Not implemented
var productData = '';
var productDetailData = '';
var mastheadData = '';
var introData = '';
var campaignBannerData = '';
var pageContentData = '';
var helpData = '';
var quicklinksData = '';
var currentSlide = 0;
var calendarMonthOffset = 0;

var availableDays = {};
var calendarDays = {};

var currentFilter = '';
var currentFilterTitle = '';
var currentFilterType = '';
var currentSort = '';
var currentPriceTo = 0;
var filteredProductCount = 0;
var currentDisplayOption = '';

var subtotalamount = 0;
var activitySuggest = null;
var locationSuggest = null;

$(function() { 
	startCarousel();
	loadNav();
    loadCartSummary();
	enablePaging(params.hasPrevPage,params.hasNextPage);
	enableSorting();
    checkAffiliateCookie();
    getUrlHashParams();
    setMainMinHeight();
    //checkCookieFilters();
    //setCookie("currentPageUID",params.uniquePageID);

    // Listen for clicks
    /*$("#cartsummary.summary").click(function(event){
        loadCart();
    });
    $("#cartsummary.detail").click(function(event){
        loadCartSummary();
    });*/

    // View options
    $("#viewoptions a").click(function(event){
        event.preventDefault();
        applyDisplayOption($(this).attr("value"))
    });


    if (params.priceTo > 0){
        currentPriceTo = params.priceTo;
    }
	if (params.isProduct) {
		productDetailData = params.productDetailData;
		//loadProductDetail();
        var date = new Date(productDetailData.firstavailabledate);
        if (!isNaN(date)) {
            godo.calendar.loadMonth(date);
        } else {
		    godo.calendar.loadMonth();
        }
        loadBackButton();
	} else
    if (params.isSearch || params.isPage) {
        setCookie("previousSearchURL", params.currentURI);

    } else {
        setCookie("previousSearchURL", null);
    }

});

function setCookie(c_name,value,exdays) {
    var exdate=new Date();
    exdate.setDate(exdate.getDate() + exdays);
    var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
    document.cookie=c_name + "=" + c_value + "; path=/";
}
function getCookie(c_name) {
    var i,x,y,ARRcookies=document.cookie.split(";");
    for (i=0;i<ARRcookies.length;i++) {
      x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
      y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
      x=x.replace(/^\s+|\s+$/g,"");
      if (x==c_name) {
        return unescape(y);
        }
    }
}

function checkAffiliateCookie() {
    var newAffiliateId = getUrlParam('affiliateId');
    //console.log('AffId URL Param: ' + newAffiliateId);
    // Is there an affiliate in this requests url params
    if (newAffiliateId && newAffiliateId != '') {
        //console.log('AffId exists');
        // Yes. First check if there is still a valid affiliateId in the cookie
        var existingAffiliateId = getCookie('AFFILIATEID');

        //console.log('Existing cookie: ' + existingAffiliateId);
        // Is there?
        if (!existingAffiliateId) {
            // No. Okay, set to the new one for 45 days
            setCookie('AFFILIATEID',newAffiliateId,45)
            //console.log('Set Cookie to ' + newAffiliateId)
        }   else {
            //console.log('Leave Cookie as ' + existingAffiliateId)
        }
    }
}

function getUrlParam(name) {
    var results = new RegExp('[\\?&]' + name + '=([^&#]*)').exec(window.location.href);
    if (results && results.length > 0) {
        return results[1];
    }
    return null;
}

function getUrlHashParams() {
        var results = new RegExp('[\\#]([^?&#]*)').exec(window.location.href);
        var friendlyparam = ''
        if (results && results.length > 0) {
            friendlyparam = results[1];
        }
        if (friendlyparam.length) {
            fuElem = friendlyUrlDeconstruct(friendlyparam)
            applyMultiFilters(fuElem)
        }

        return true
}

function friendlyUrlConstructElement(filter,filterType,priceTo,sort,page,display) {
    var searchElementsMap = friendlyUrlElements()
    var fuParams = ''
    $.each(searchElementsMap, function(e, element) {
            //console.log(element.sefid)
            //console.log(e)

            if (e == 'price' && parseInt(priceTo) > 0) {
               fuParams +=  element.sefid + priceTo + '-'
            }
            if (e == 'page' && parseInt(page) > 1) {
               fuParams +=  element.sefid + page + '-'
            } else
            if (e == 'sort' && sort.length > 0) {
               fuParams +=  element.sefid + sort + '-'
            }  else
            if (e == 'display' && display.length > 0) {
               fuParams +=  element.sefid + display + '-'
            } else
            if (e == filterType ) {
               //console.log('EQUAL: ' + element.sefid + filter)
               fuParams +=  element.sefid + filter + '-'
            }
    });

    // Chop off the trailing hyphen
    if(fuParams.length > 1 && fuParams.substring(fuParams.length-1,fuParams.length) == '-') {
        fuParams = fuParams.slice(0,fuParams.length-1)
    }

    return fuParams

}

function friendlyUrlDeconstruct(productSearchURI) {

    var searchElementsMap = friendlyUrlElements()

    // Slit the productSearchURI by hyphen
    var searchElementsMap = friendlyUrlElements()
    var processParams = {}
    var workingstring = productSearchURI
    var baseslices = productSearchURI.split("-")
    var workingslices = baseslices

    $cnt = workingslices.length;
    $i = $cnt - 1;

    var gatheringelements = ''
    while($i >= 0){
        gatheringelements = workingslices.pop().concat(['-'],gatheringelements)

        $.each(searchElementsMap, function(e, element) {
            //console.log(element.sefid)
            //console.log('Index of sefid: ' +gatheringelements.indexOf(element.sefid))
            if (gatheringelements.indexOf(element.sefid) != -1) {
                var thiselement = {}
                var elemValue = gatheringelements.replace(element.sefid,'')

                // Chop off the trailing hyphen
                if(elemValue.length > 1 && elemValue.substring(elemValue.length-1,elemValue.length) == '-') {
                    elemValue = elemValue.slice(0,elemValue.length-1)
                }
                thiselement["filter"] = elemValue

                thiselement["filterType"] = e

                processParams[element.sefid] = thiselement
                gatheringelements = ''
            }
        });
        $i--;
    }

    return processParams

}

function friendlyUrlElements(productSearchURI) {

    return {
        "category": {
            sticky: true,
            priority: 10000,
            sefid: "experience-",
            titlephrase: "_e_ activities",
            headerLevel: "H1"
            },
        "location": {
            sticky: true,
            priority: 11000,
            sefid: "activities-in-",
            titlephrase: "in _e_",
            headerLevel: "H1"
            },
        "phrase":     {
            sticky: true,
            priority: 11050,
            sefid: "contains-",
            titlephrase: "containing _e_",
            headerLevel: "H1"
            },
        "availability":     {
            sticky: false,
            priority: 12000,
            sefid: "available-",
            titlephrase: "available _e_",
            note: "Indicates availability",
            headerLevel: "H1"
            },
        "coordinates": {
            sticky: false,
            priority: 12500,
            sefid: "coordinates-",
            titlephrase: "near coordinates _e_",
            headerLevel: "H2"
            },
        "price": {
            sticky: false,
            priority: 13000,
            sefid: "prices-under-",
            titlephrase: "for under _e_",
            headerLevel: "H2"
            },
        "special": {
            sticky: false,
            priority: 14000,
            sefid: "on-special-",
            titlephrase: "on special",
            flag: true,
            headerLevel: "H2"
            },
        "sort": {
            sticky: false,
            priority: 20000,
            sefid: "sort-",
            titlephrase: "sort _e_",
            headerLevel: "H2"
            },
        "page": {
            sticky: false,
            priority: 17000,
            sefid: "page-",
            titlephrase: "page _e_",
            headerLevel: "H2"
            },
        "display": {
            sticky: false,
            priority: 30000,
            sefid: "display-",
            titlephrase: "display _e_",
            headerLevel: "H2"
            }
    };
}

function applyDisplayOption(display){
    if (display.length) {
        $("#godoProducts").attr("class", display);
        $("#viewoptions .selected").removeClass("selected");
        $("#viewoptions a[value="+display+"]").addClass("selected");
        currentDisplayOption = display
        setFilterHistory()
    }
}

function setFilterHistory() {

    var newHash = friendlyUrlConstructElement(currentFilter,currentFilterType,currentPriceTo,currentSort,params.page,currentDisplayOption)
    window.location.hash = newHash
}

function resetPaging() {
	params.page = 1;	
}

function enablePaging(hasPrevPage,hasNextPage) {
	// REPLACE with a TEMPLATE. load every time. EASIER MAYBE
	var main2Top = $("#godo-main2").offset().top;
	
	$(".pagingoptions a").addClass('disabled').unbind('click');
	if (hasPrevPage == true) {		
		$(".pagingoptions .previous").removeClass('disabled').click(function(event) {
            event.preventDefault();
			getProductPage(-1);
            //scrollToNewPage();			
		});
	} else {
		$(".pagingoptions .previous").click(function(event) {
            event.preventDefault();
		});		
	}
	if (hasNextPage == true) {
		$(".pagingoptions .next").removeClass('disabled').click(function(event) {
            event.preventDefault();
			getProductPage(1);
            scrollToNewPage();
		});
	} else {
		$(".pagingoptions .next").click(function(event) {
            event.preventDefault();		
        });
	}
	
	function scrollToNewPage() {
        $('html, body').animate({
            scrollTop: main2Top
        }, 300);	
	}
}

function enableSorting() { 
	$("#sortoptions a.sortprice").click(function(event) {
        event.preventDefault();
		if (currentSort == 'price-asc') {
			sortProducts('price-desc');
		} else {
			sortProducts('price-asc');
		}
	});
	$("#sortoptions a.sortname").click(function(event) {
        event.preventDefault();	
        if (currentSort == 'name-asc') {
        	sortProducts('name-desc');
        } else {
        	sortProducts('name-asc');
        }
	});	
}

function loadBackButton() {
    $(".back").html('<a href="/">&laquo; Back</a>').click(function() {
        history.back(1)
        return false
    });
}

function sortProducts(newSort,page){
	// Sorting
	// Price
	$("#sortoptions a").removeClass('selected');
	if (newSort == 'price-asc') {
		params.jsonProducts.sort(function(a,b){
			return a.MINPRICE - b.MINPRICE
		});		
		currentSort = 'price-asc';
		$("#sortoptions a.sortprice").addClass('selected');
	} else 
	if (newSort == 'price-desc') {
		params.jsonProducts.sort(function(a,b){
			return b.MINPRICE - a.MINPRICE
		});		
		currentSort = 'price-desc';
		$("#sortoptions a.sortprice").addClass('selected');
	} else	
	// Name
	if (newSort == 'name-asc') {
		params.jsonProducts.sort(function(a,b){
			//return a.NAME - b.NAME
		   var compA = a.NAME.toUpperCase();
		   var compB = b.NAME.toUpperCase();
		   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
		});		
		currentSort = 'name-asc';
		$("#sortoptions a.sortname").addClass('selected');
	} else 
	if (newSort == 'name-desc') {
		params.jsonProducts.sort(function(a,b){
			//return b.NAME - a.NAME
			var compA = a.NAME.toUpperCase();
			var compB = b.NAME.toUpperCase();
			return (compB < compA) ? -1 : (compB > compA) ? 1 : 0;			
		});		
		currentSort = 'name-desc';
		$("#sortoptions a.sortname").addClass('selected');
	}
    if (page == null || page == 1) {
	    resetPaging();
    }
	getProductPage(0);
	return false;
}

function setSearchDescription() {
	godo.util.template.fetch("subIntro", function(){

        var subIntroModel = {
                hascategory: false,
		        haslocation: false,
		        haskeyword: false,
                hasfilter: false,
                haspricefilter: false,
		        category: "",
		        location: "",
		        keywords: "",
                filter : "",
                unit: "activities",
                count: filteredProductCount
        }
		if (params.criteria.Subcategory.TITLE != '') {
			subIntroModel.category = params.criteria.Subcategory.TITLE;
			subIntroModel.hascategory = true;
		} else if (params.criteria.Category.TITLE != '') {
			subIntroModel.category = params.criteria.Category.TITLE;
			subIntroModel.hascategory= true;
		}
		if (params.criteria.Region.TITLE != '') {
			subIntroModel.location = params.criteria.Region.TITLE;
			subIntroModel.haslocation = true;
		} else if (params.criteria.State.TITLE != '') {
			subIntroModel.location = params.criteria.State.TITLE;
			subIntroModel.haslocation = true;
		}
		if (params.criteria.Phrases != '' && !params.hideKeyword) {    // Keyword is hidden on Landing pages
			subIntroModel.keywords = params.criteria.Phrases;
			subIntroModel.haskeyword = true;
		}
        if (currentFilter != '') {
            subIntroModel.filter = currentFilterTitle;
            subIntroModel.hasfilter = true;
        }
		if (filteredProductCount == 1) {
			subIntroModel.unit = "activity";
		}
        if (currentPriceTo > 0) {
            subIntroModel.pricefilter = currentPriceTo;
            subIntroModel.haspricefilter = true;
            $("#priceToDisplay a").html('Up to $'+currentPriceTo);
        } else {
            $("#priceToDisplay a").html('No limit');
        }


        // Pass the model to the view and render using mustache template
        godo.util.template.make("subIntro", subIntroModel, function(html){
            $("#resultsTitle").empty();
            html.appendTo("#resultsTitle");
        });

	});

}

function loadCheckout() {

	//~~~~~~~~~~~~ CART DETAIL JSON ~~~~~~~~~~~~~~~~~~//

    $.ajax({
        url: cartDetailJSONUrl,
        dataType: "json",
        success: function(cartjson){
            //console.log(cartjson.items.toString())
            //location.href=checkoutUrl

            // Set a form field with the cartjson
            $("#cartproxyform #booking").val(cartjson.items.toString())




// TODO: Assess how this whole 2 session thing will work. Best to keep it stateless,
//       but that means posting a form around each time.
//       Might be best, but need to rip Checkoutcontroller apart, Maybe separate the validation service, so it can handle JSON rather than session.godocart
//       Then have another controller CartController for local http and CheckoutController for https





            //$("#cartproxyform").submit();
            //location.href=checkoutUrl
            // Post the form (this will avoid issue of ajax post to https)

           /* $.post(checkoutUrl, cartjson,function() {
                console.log(cartjson)
                location.href=checkoutUrl
            });*/
            //return false;
        }
    });
    return


}

function loadCart() {

	//~~~~~~~~~~~~ CART DETAIL ~~~~~~~~~~~~~~~~~~//
	$.ajax({
        url: cartDetailUrl,
        dataType: "html",
        data: ({siteUrl: params.siteUrl}),
        success: function(carthtml){
            //$("#cartsummary").empty()
            $("#cartdetail").empty().append(carthtml).slideDown().click(function(event){
                //.append('<div class="pagefade"></div>')
                //event.preventDefault();
                //loadCartSummary();
                $("#cartdetail").slideUp();
            });
        }
    });
    /*$("#cartsummary.detail").click(function(event){
        event.preventDefault();
        loadCartSummary();
        return false;
    });*/
    return false;
}

function loadCartSummary() {

	//~~~~~~~~~~~~ CART SUMMARY ~~~~~~~~~~~~~~~~~~//

    var apisessionid = getCookie("apisessionid");
    var apisessioncachekey = getCookie("apisessioncachekey");
    var randomiser = new Date().getMilliseconds();
    if (!apisessioncachekey) {
        setCookie("apisessioncachekey",randomiser)
        apisessioncachekey = randomiser;
    }
    if (!apisessionid) {
        //console.log('No apisessionid: ' + apisessionid)
        setCookie("apisessionid",'freshcart')
        apisessionid = 'freshcart';
    }

    //console.log('before getting cart. apisessionid: ' + apisessionid)
	$.ajax({
        url: cartSummaryUrl + apisessionid + '/' + apisessioncachekey, //'https://' + params.siteHttpsURL + cartSummaryUrl,
        dataType: "html",
        data: ({
                siteUrl: params.siteUrl,
                random: randomiser
                }),
        success: function(carthtml){
            $("#cartdetail").empty().hide()
            //console.log(carthtml);
            $("#cartsummary").empty().append(carthtml).slideDown();

            //console.log('We have: ' + $("#apisessionid").text());
            setCookie("apisessionid",$("#apisessionid").text());
        }
    });
    return false;
}

function loadNav() {

	//~~~~~~~~~~~~ CATEGORIES ~~~~~~~~~~~~~~~~~~//
	$.ajax({
        url: categoriesJSONUrl,
        data: ({
        	siteUrl: params.siteUrl
   		}),
        dataType: "json",
        success: function(data){

            var categoryModel = buildCategoryModel(data);
            // Create the autosuggest
            activitySuggest = $("#activitykeyworddisplay").suggest({ data: categoryModel });
            activitySuggest.node.bind("focus", function(){
                locationSuggest.close();
            });
        }
    });

	//~~~~~~~~~~~~ LOCATIONS ~~~~~~~~~~~~~~~~~~//
	$.ajax({
        url: locationsJSONUrl,
        data: ({
        	siteUrl: params.siteUrl
        }),
        dataType: "json",
        success: function(data){

            var locationModel = buildLocationModel(data);

            // Create the autosuggest
           	locationSuggest = $("#locationkeyworddisplay").suggest({ data: locationModel });
            locationSuggest.node.bind("focus", function(){
                activitySuggest.close();
            });           	

        }
    });
}

function loadTinySearchNav() {

	//~~~~~~~~~~~~ CATEGORIES ~~~~~~~~~~~~~~~~~~//
	$.ajax({
        url: categoriesJSONUrl,
        data: ({
        	siteUrl: params.siteUrl
   		}),
        dataType: "json",
        success: function(data){

            var categoryModel = buildCategoryModel(data);
            // TODO: Populate select box

            $.each(categoryModel, function(key, value) {
                 $('#tinysearchcategories')
                      .append($('<option>', { value : key })
                      .text(value));
            });

        }
    });

	//~~~~~~~~~~~~ LOCATIONS ~~~~~~~~~~~~~~~~~~//
	$.ajax({
        url: locationsJSONUrl,
        data: ({
        	siteUrl: params.siteUrl
        }),
        dataType: "json",
        success: function(data){

            var locationModel = buildLocationModel(data);
            // TODO: Populate select box

            $.each(locationModel, function(key, value) {
                 $('#tinysearchlocations')
                      .append($('<option>', { value : key })
                      .text(value));
            });

        }
    });
}


function buildCategoryModel(data) {
    var categoryModel = {
        level1: [0],
        items: [{
            name: "Anything",
            value: "Anything",
            href: "",
            id: "cat-0",
            type: "all"
        }]
    };
    $.each(data.CATEGORIES, function(c, category){

        // Apply any logic here so we can pass a ready-to-render object to the jquery template
        var catModel = {
            name: category.NAME,
            value: category.SEFNAME,
            href: params.contextPath + params.categoryPrefix  + category.SEFNAME + '-' + params.locationURIParam,
            id: "cat-" + category.ID,
            children: []
        };

        // Add an all option if required
        if (category.SUBCATEGORIES && category.SUBCATEGORIES.length > 0) {
            var subcatModel = {
                name: "All " + category.NAME,
                value: category.SEFNAME,
                href: params.contextPath + params.categoryPrefix  + category.SEFNAME + '-' + params.locationURIParam,
                id: "cat-" + category.ID,
                type: "all"
            }
            categoryModel.items.push(subcatModel);
            catModel.children.push(categoryModel.items.length - 1);

            // Loop through subcat, create model and add to parent model
            $.each(category.SUBCATEGORIES, function(j,subcategory){
                var subcatModel = {
                    name: subcategory.NAME,
                    value: subcategory.SEFNAME,
                    href: params.contextPath + params.categoryPrefix  + subcategory.SEFNAME + '-' + params.locationURIParam,
                    id: "subcat-" + subcategory.ID
                }
                categoryModel.items.push(subcatModel);
                catModel.children.push(categoryModel.items.length - 1);
            });
        }

        categoryModel.items.push(catModel);
        categoryModel.level1.push(categoryModel.items.length - 1);

    });
    return categoryModel

}

function buildLocationModel(data) {
    var locationModel = {
        level1: [0],
        items: [{
            name: "Anywhere",
            value: "Anywhere",
            href: "",
            id: "state-0",
            type: "all"
        }]
    };
    $.each(data.LOCATIONS, function(d, state){

        // Apply any logic here so we can pass a ready-to-render object to the jquery template
        var stateModel = {
            name: state.NAME,
            value: state.SEFNAME,
            href: params.contextPath + params.categoryURIParam + params.locationPrefix + state.SEFNAME,
            id: "state-" + state.ID,
            children: []
        };

        // Add an all option if required
        if (state.REGIONS && state.REGIONS.length > 0) {
            var regionModel = {
                name: "All " + state.NAME,
                value: state.SEFNAME,
                id: "state-" + state.ID,
                type: "all"
            }
            locationModel.items.push(regionModel);
            stateModel.children.push(locationModel.items.length - 1);

            // Loop through subcat, create model and add to parent model
            $.each(state.REGIONS, function(j,region){
                var regionModel = {
                    name: region.NAME,
                    value: region.SEFNAME,
                    href: params.contextPath + params.categoryURIParam + params.locationPrefix + region.SEFNAME,
                    id: "region-" + region.ID
                }
                locationModel.items.push(regionModel);
                stateModel.children.push(locationModel.items.length - 1);
            });
        }

        locationModel.items.push(stateModel);
        locationModel.level1.push(locationModel.items.length - 1);
    });
    return locationModel;
}

//~~~~~~~~~~~~ PRODUCTS ~~~~~~~~~~~~~~~~~~//

function getProductPage(inc,filterType,filter) {
	// Increment the page (pos or neg) without going negative
	params.page = eval(params.page + inc);

	//params.cardQuota = 20;
	if (params.page < 1) params.page = 1;
	var startRow = eval(0 + (params.page*params.cardQuota) - params.cardQuota);
	var endRow = startRow + params.cardQuota;
	var hasPrevPage = true;
	var hasNextPage = true;			
	//var subSetProducts = params.jsonProducts.slice(startRow,endRow);
	var filteredProducts = [];

	if (currentFilterType != '' || currentPriceTo > 0) {
		$.each(params.jsonProducts, function(j,p){
            var pFilters = p.FILTERS.split(" ");
            $.each(pFilters, function(k,filter){
                if (currentPriceTo == 0 || parseInt(p.MINPRICE) <= parseInt(currentPriceTo)) {
                    if (filter.toLowerCase() == currentFilter.toLowerCase() || currentFilter == '') {
                        filteredProducts.push(p);
                        return false;
                    }
                }
            });
		});
	} else {
		filteredProducts = params.jsonProducts;
	}

    // Set the global count
	filteredProductCount = filteredProducts.length;
	
	if (filteredProducts.length < params.cardQuota) {			
		startRow = 0;
		endRow = filteredProducts.length;		
		//hasNextPage = false;
	} 
	
	if (params.page == 1) {
		hasPrevPage = false;
	}	
	
	var subSetProducts = filteredProducts.slice(startRow,endRow);
	
	if (subSetProducts.length < params.cardQuota){
		hasNextPage = false;		
	}
	enablePaging(hasPrevPage,hasNextPage);
	
	$("#godoProducts").empty();	
	
	godo.util.template.fetch("productCard", function(){		
		$.each(subSetProducts, function(j,p){
			
			//if (p.ADID > 0) {
			//	p.ADID = p.ADID
			//}
			var prodPriceLabel = "";
			var prodSpecialClass = "";
			var prodSpecial = "";
			if (p.MINPRICE != p.MAXPRICE) {
				prodPriceLabel = "from";
			}
			if (p.ONSPECIAL == 1 && p.SPECIALOFFERTEXT.length > 0) {
				prodSpecialClass = "sale save";
				prodSpecial = p.SPECIALOFFERTEXT;
			}
			var prodCardModel = {
				name : p.NAME,
				href : "/activity/" + p.PRODUCTCODE, //p.FU,
				adid : p.ADID,
				imagesrc : params.mediaBaseUrl + "/media/products/250x168/" + p.IMAGEFILE,
				location: p.LOCATION,
				price : p.MINPRICE,
				summary : p.MARKETDESCRIPTION,
				//filters : p.CATEGORYFU + ' ' + p.SUBCATEGORYFU + ' ' + p.STATEFU + ' ' + p.REGIONFU + ' under-' + p.PRICEBRACKET,
				//filters: p.FILTERS,
				pricelabel : prodPriceLabel,				
				specialclass : prodSpecialClass,
				special: prodSpecial		
			}
			// Pass the model to the view and render using mustache template
			godo.util.template.make("productCard", prodCardModel, function(html){
				html.appendTo("#godoProducts");
			});	
		});

	});

    // Create the new fu params and set to history
    setFilterHistory();


}

function resetCarousel(newIndex) {
	$slides = $("#slides .slide");
	slideCount = $slides.length;
	
	if (newIndex > currentSlide) {
		diffSlides = newIndex - currentSlide;
    } else
    if (newIndex < currentSlide ){
    	diffSlides = slideCount-currentSlide+newIndex;    	
    }  else {
    	diffSlides = 0;
    }   
	for (var i=1; i <= diffSlides; i++){
		setCarousel($slides);
	}
}

function setCarousel(slides) {
	var $slides = slides;
	var slideCount = $slides.length;

	if (currentSlide+1 >= slideCount) {
        currentSlide = 0;
    } else {
        currentSlide++;
    }            

    $slides.each(function(index, slide) {
   	 //setCarouselSlide(index,slide);
    	 var left = parseInt(slide.style.left);
         var newleft = left - 100;
         if (slideCount == 1){
        	 newleft = 0; 
         }
         if (newleft < -100) {
             newleft = ((slideCount-1) * 100) - 100;
         }
         if (newleft < 100 && newleft > -101) {
             $(slide).addClass("animated");
         } else {
             $(slide).removeClass("animated");
         }
         $(slide).css("left", newleft + "%");
         
         $("#slider-nav li.selected").addClass("unselected");
         $("#slider-nav li.selected").removeClass("selected");
         $($("#slider-nav li")[currentSlide]).addClass("selected");
         $("#slider-nav li.selected").removeClass("unselected");
         // Hide sliderNav if only one slide
         if (slideCount == 1){
        	 $("#slider-nav").hide();	 
         }
    	
    });
}

function startCarousel() {
 
	 var $slides = $("#slides .slide");
     if ($slides.length > 1) {    	 
	     var autoSlideTimer = setInterval(function(){
	    	 setCarousel($slides);
	     }, 6000);
     } else {
    	 setCarousel($slides);
     }
}


function hideStaticPage() {
	$("#godoPage").hide();
}
function loadStaticPage() {
	$("#godoPage").empty();
	//$("#godoPage").html(pageContentData.BODY);
	
	godo.util.template.fetch("page", function(){
		
		var pageModel = {
			title:  pageContentData.TITLE,
			body:  pageContentData.BODY
		}
					
		// Pass the model to the view and render using mustache template
	    godo.util.template.make("page", pageModel, function(html){
	        html.appendTo("#godoPage");
	    });		

	});
}

function loadHelp() {
	
	$("#godoHelpMenu").empty();
	$("#godoHelp").empty();
		
	// Load the menu
	godo.util.template.fetch("helpMenu", function(){
		// TODO: Set page title using helpData.SITEMAP.TITLE 
		
		var helpMenu = {
				title: "All help topics",
				href: params.contextPath + "help",
				children: []
		}
		
		$.each(helpData.SITEMAP.TOPICS, function(i,topic){
			
			var menuItemModel = {
					title:  topic.TITLE,
					href:  params.contextPath + topic.HREF
			}
			helpMenu.children.push(menuItemModel);
		});
		
		// Pass the model to the view and render using mustache template
	    godo.util.template.make("helpMenu", helpMenu, function(html){
	        html.appendTo("#godoHelpMenu");
	    });
		
	});
	
	// Check that we have a specific topic. If not then use HelpHome template 
	if (helpData.TOPIC.HTML) {
		
		godo.util.template.fetch("helpTopic", function(){
			var helpTopicModel = {
					title: helpData.TOPIC.TITLE,
					html: helpData.TOPIC.HTML				
			}
			// Pass the model to the view and render using mustache template
		    godo.util.template.make("helpTopic", helpTopicModel, function(html){
		        html.appendTo("#godoHelp");
		    });		
		});
		
	} else {

		godo.util.template.fetch("helpHome", function(){
			
			var helpHomeModel = {
				children: []					
			}
			$.each(helpData.SITEMAP.TOPICS, function(i,topic){
				
				var homeItemModel = {
						title:  topic.TITLE,
						href:  params.contextPath + topic.HREF,
						imagesrc: topic.image,
						summary: topic.SUMMARY
						
				}
				helpHomeModel.children.push(homeItemModel);
			});
			// Pass the model to the view and render using mustache template
		    godo.util.template.make("helpHome", helpHomeModel, function(html){
		        html.appendTo("#godoHelp");
		    });			
			
		});		
		
	}	
}
function loadCampaignBanners() {	
	
	$("#godoCampaigns").empty();
	if (campaignBannerData.length > 0){	
		godo.util.template.fetch("banner", function(){
						
			// Loop through subcat, create model and add to parent model
			$.each(campaignBannerData, function(i,campaignBanner){
				//var imagePathPrefix = "http://www.godo.au.dev/media/products/250x168/";
				
				var bannerModel = {
					name:  campaignBanner.H1,
					href: "",
					imagesrc:  campaignBanner.IMAGE, 
					location: "",
					price: "",
					summary:  campaignBanner.P
				}
							
				// Pass the model to the view and render using mustache template
			    godo.util.template.make("banner", bannerModel, function(html){
			        html.appendTo("#godoCampaigns");
			    });		
				
			});		
						

		});			
	}	
}

function setMainMinHeight() {
    var filterHeight = 55; 
    $("#godoFilters > div").each(function(){ 
        filterHeight += parseInt(($(this).css("height"))); 
    });
    $('#godo-main2').css("min-height", filterHeight+"px");

}

//~~~~~~~~~~~~ SPONSORED PRODUCT ADS ~~~~~~~~~~~~~~~~~~//
function clickProduct(adId,url) {
	//window.location.href = '/click/'+ adId;
	// TODO: Track the click via Ajax
	window.location.href = url;
}
