﻿
/***** Variables *****/

var brandId = 1324;         // Taster's Choice brand id. Tie to web.config?
//var brandId = 1261;         // Coffee-mate brand id for testing
var currentPage = 1;        // Current page of store results
var pageSize = 10;          // Number of store results per page
var lastSearchUPC = "";     // 
var lastSearchZip = "";     // Stores previous search query
var lastSearchRadius = "";  //

/*****AJAX functions *****/

// Request producst list JSON; call to start process
function getAllProducts() {
    var myAjax = new Ajax.Request(
        '../WTBService.asmx/GetAllProducts',       //url
        {
            method: 'POST',
            parameters: { brandId:brandId },
            onSuccess: readProducts
        });
}

//Use these instead of GetAllProducts if separating categories and products fields

// Request categories list JSON; call to start process
//        function getCategories() {
//            var myAjax = new Ajax.Request(
//	            '../WTBService.asmx/GetCategories',       //url
//	            {
//		            method: 'POST',
//		            parameters: {brandId:brandId},
//		            onSuccess: readCategories
//		        });
//        }

// Request producst list JSON based on category
//		function getProducts(categoryId) {
//		    var myAjax = new Ajax.Request(
//	            '../WTBService.asmx/GetProducts',       //url
//	            {
//		            method: 'POST',
//		            parameters: {categoryId:categoryId},
//		            onSuccess: readProducts
//		        });
//		}

// Store search
function getLocations(upc, zip, radius, currentPage, pageSize) {
    var myAjax = new Ajax.Request(
        '../WTBService.asmx/GetPagedLocations',       //url
        {
            method: 'POST',
            parameters: {upc:upc, zip:zip, radius:radius, currentPage:currentPage, pageSize:pageSize},
            onSuccess: readLocations
        });
}

//function readCategories(t) {
//    var categories = evalJSONResponse(t);
//    categories.each( function(c, i) { $('ddlCategory').options[i+1] = new Option(c.Name, c.Id); });
//}

//Handle response for GetAllProducts/GetProducts
function readProducts(t) {
    var products = evalJSONResponse(t);
	//if there is a matching sku, default the product list to that field
 	var skuQS = window.location.href.toQueryParams();
	var sku = skuQS['sku'];
	
	//Add each product to the drop-down
	products.each( function(p, i) { 
		$('ddlProducts').options[i+1] = new Option(p.Name, p.UPC); 
		if(p.UPC == sku){
			$('ddlProducts').options[i+1].selected = true;
		}
    });  
    $('ddlProducts').enable();  //Enable products field once loaded
}



//Handle response for GetLocations
function readLocations(t) {
    var locations = evalJSONResponse(t);
    $('wtbSearchDiv').hide();
    if (locations.Count == 0) { $('wtbNoResultsDiv').show(); }
    else
    {
        $('productNameSpan').innerHTML = $('ddlProducts').options[$('ddlProducts').selectedIndex].text;
        $('radiusSpan').innerHTML = $F('ddlRadius');
        $('zipSpan').innerHTML = $F('txtZip');
        $('wtbResults').innerHTML = "";             //clear results
        $('wtbPaging').innerHTML = "";              //clear paging
        locations.Stores.each( function(s) {
                new Insertion.Bottom('wtbResults', createStoreResult(s));
        });
        $('wtbResultsDiv').show();
        
        //Paging
        var numPages = Math.ceil(locations.Count / pageSize);
        var pagingHTML = "";
        //Previous button
        if(numPages > 1 && currentPage != 1)
        { pagingHTML += '<a href="javascript:goToPage(currentPage - 1);void(0);">&lt;&lt; Previous</a>&nbsp;&nbsp;&nbsp;'; }
        //Page links
        for(var i=1;i <= numPages; i++)
        {
            if( i == currentPage) { pagingHTML += i; }
            else { pagingHTML += '<a href="javascript:goToPage(' + i + ');void(0);">' + i + '</a>'; }
            if( i != numPages ) { pagingHTML += ' | '; }        //seperator
        }
        //Next button
        if(numPages > 1 && currentPage != numPages)
        { pagingHTML += '&nbsp;&nbsp;&nbsp;<a href="javascript:goToPage(currentPage + 1);void(0);">Next &gt;&gt;</a>'; }
        new Insertion.Bottom('wtbPaging', pagingHTML);
    }    
}

/***** Utility Functions *****/

//function categoryChange()
//{
//    var catId = $F('ddlCategory');
//    if (catId != "-1") getProducts(catId);
//}

// Read form fields and submit store search query
function wtbSearch()
{
    lastSearchUPC = $F('ddlProducts');
    lastSearchZip = $F('txtZip');
    lastSearchRadius = $F('ddlRadius');
    getLocations(lastSearchUPC, lastSearchZip, lastSearchRadius, currentPage, pageSize);
}

// Return HTML string for store result summary
function createStoreResult(store)
{
    var result = '<div class="resultRow">\n';
    result += '<div class="storCol"><span>' + store.Name + '</span></div>\n';
    result += '<div class="addrCol"><a href="http://maps.google.com/maps?q=' + store.FullAddress.replace(/ /g,"+") + '">' + store.FullAddress + '</a></div>\n';
    result += '<div class="phoneCol"><span>' + store.Phone + '</span></div>\n</div>\n';
    return result;
}

/***** Paging functions *****/

// Go to page n of results
function goToPage(n) 
{
    currentPage = n;
    getLocations(lastSearchUPC, lastSearchZip, lastSearchRadius, currentPage, pageSize);
}