// JavaScript Document

var pgNumActive = 1;

/**********************************************************************
******************************* SORTING *******************************
**********************************************************************/
function asgnSortHandler () {
	/* Assigns an onchange event handler to the sort drop-down box. */
	var srt = $('selectSortOrder');
	if (!srt) return false;
	srt.onchange = function() { prepAndSend('sortchange'); return false; }
	return true;
}

function getSortVal() {
	var sortType = 'N'; // Default to newest first
	var srt = $('selectSortOrder');
	if (srt) {
		sortType = srt.options[srt.selectedIndex].value;
	}
	return sortType;
}

function setSortSelection(s) {
	if (!s) return;
	var srt = $('selectSortOrder');
	if (!srt) return;
	for (var y=0; y < srt.options.length; y++) {
		if (srt.options[y].value == s) srt.options[y].selected = true;
	}
}
/**********************************************************************
***************************** END SORTING *****************************
**********************************************************************/


/**********************************************************************
******************************** FACETS *******************************
**********************************************************************/
function updFacetCounts(els) {
	/* Update the parenthesized product counts per facet. */
	var domEl = '';
	for (var i=0; i < els.length; i++) {
		// Update Count
		domEl = $('FctSpn_' + els[i].elm);
		if (domEl) domEl.innerHTML = '(' + els[i].ct + ')';
		domEl = $('FctLi_' + els[i].elm);
		if (domEl) {
			if (els[i].ct == 0) domEl.style.display='none';
			else domEl.style.display='';
		}
		// Update abled/disabled
		//domEl = $('FctRdo_' + els[i].elm);
		//if (!domEl) domEl = $('FctCbx_' + els[i].elm);
		//if (domEl) domEl.disabled = (els[i].ct)?false:true;
		// Update abled/disabled text color
		//domEl = $('FctText_' + els[i].elm);
		//if (!domEl) domEl = $('FctText_' + els[i].elm);
		//if (domEl) domEl.style.color = (els[i].ct)?'#666666':'#b3b3b3';
	}
}

function facetInfo (elmID,isOn) {
	this.id = elmID;
	this.isOn = isOn;
}

function getFacetInfo (elmID,isOn) {
	return new facetInfo(elmID,isOn);
}

function bundleFacetVals() {
	var fcel = new Array();
	facetWrap = $('divFacets');
	if (!facetWrap) return fcel;
	// Grab checkbox settings
	var elms = facetWrap.getElementsByTagName('input');
	for (var i=0; i < elms.length; i++) {
		if (hasClass(elms[i],'FctCbx') || hasClass(elms[i],'FctRdo')) {
			var aryID = elms[i].id.split('_');
			var elmid  = aryID[1];
			fcel.push(getFacetInfo(elmid,elms[i].checked));
		}
	}
	return fcel;
}

function fctResetClicked(id) {
	var ulWrap = $(id.replace('FctReset_','FctGrp_'));
	if (!ulWrap) return true;
	var elms = ulWrap.getElementsByTagName('input');
	for (var i=0; i < elms.length; i++) {
		if (hasClass(elms[i],'FctCbx') || hasClass(elms[i],'FctRdo')) {
			elms[i].checked = false ;
		}
	}
}

function fctMainResetClicked() {
	var facetWrap = $('divFacets');
	if (!facetWrap) return false;
	var elms = facetWrap.getElementsByTagName('a');
	for (var i=0; i < elms.length; i++) {
		if (hasClass(elms[i],'FctReset')) fctResetClicked(elms[i].id);
	}
	if (elms.length) prepAndSend('fctclick');
	return false;
}

function setFacetSelections(popIns) {
	// Facets
	var facetWrap = $('divFacets');
	if (!facetWrap) return;
	var elms = facetWrap.getElementsByTagName('input');
	var idSegs = '';
	var elmID = '';
	for (var y=0; y < popIns.length; y++) {
		domEl = $('FctRdo_' + popIns[y].id);
		if (!domEl) domEl = $('FctCbx_' + popIns[y].id);
		if (domEl) domEl.checked = popIns[y].isOn;
	}
}

function addFacetProgress() {
	facetWrap = $('divFacets');
	if (!facetWrap) return true;
	
	var spans = facetWrap.getElementsByTagName('span');
	for (var i=0; i < spans.length; i++) {
		sid = spans[i].id.split('_');
		if (sid.length == 2 && sid[0] == 'FctSpn') {
			var progress_img = new Image;
			progress_img.src = 'images/progress3.gif';
			removeChildren(spans[i]);
			spans[i].appendChild(progress_img);			
		}
	}
}

function asgnFacetHandlers () {
	/* Assigns appropriate event handlers to the facet checkboxes, facet 
	radio buttons, and facet reset links */
	var facetWrap = $('divFacets');
	if (!facetWrap) return false;
	// Checkboxes and radio buttons...
	var elms = facetWrap.getElementsByTagName('input');
	for (var i=0; i < elms.length; i++) {
		if (hasClass(elms[i],'FctCbx') || hasClass(elms[i],'FctRdo')) {
			elms[i].onclick = function() { prepAndSend('fctclick'); }
		}
	}
	// 'Reset' links...
	var elms = facetWrap.getElementsByTagName('a');
	for (var i=0; i < elms.length; i++) {
		if (hasClass(elms[i],'FctReset')) {
			elms[i].onclick = function() { fctResetClicked(this.id); prepAndSend('fctclick'); return false; }
		}
	}
	var elm = $('MainReset');
	if (elm) elm.onclick = fctMainResetClicked;
}
/**********************************************************************
**************************** END FACETS *******************************
**********************************************************************/


/**********************************************************************
**************************** THUMBNAILS *******************************
**********************************************************************/
function updThumbs (html) {
	/* Move new product thumbs to the page. */
	var pa = $('divThumbs');
	if (pa) pa.innerHTML = html;
}

function showNoResults() {
	/* Show "No results" message in thumbnail area. */
	var pa = $('divThumbs');
	if (!pa) return false;
	var newDiv = document.createElement("div");
	newDiv.style.padding = '70px 0 70px 20px';
	newDiv.style.color = '#999999';
	newDiv.style.fontSize = '18px';
	noResText=document.createTextNode("No matching products were found");
	newDiv.appendChild(noResText);
	removeChildren(pa);
	pa.appendChild(newDiv);
}

function addProdAreaProgress() {
	var thumbArea = $('divThumbs');
	if (!thumbArea) return true;
	removeChildren(thumbArea);
	var progress_img = new Image;
	progress_img.src = 'images/thumbprogress.gif';
	var newDiv = document.createElement("div");
	newDiv.style.textAlign = 'center';
	newDiv.style.paddingTop = '70px';
	newDiv.style.paddingBottom = '70px';
	newDiv.appendChild(progress_img);
	thumbArea.appendChild(newDiv);			
}
/**********************************************************************
************************** END THUMBNAILS *****************************
**********************************************************************/


/**********************************************************************
************************* THUMBS PER PAGE *****************************
**********************************************************************/
function asgnNumPerPageHandler() {
	/* Assigns an onchange event handler to the 'per page' drop-down box. */
	var spp = $('selectPerPage');
	if (!spp) return;
	spp.onchange = function() { prepAndSend('perpagechange'); return false; }
	return true;
}

function setThumbsPerPage(pc) {
	var spp = $('selectPerPage');
	if (!spp) return;
	for (var y=0; y < spp.options.length; y++) {
		if (spp.options[y].value == pc) spp.options[y].selected = true;
	}
}

function getPageCount() {
	var pgCount = 12; // Default to 12
	var pgDD = $('selectPerPage');
	if (pgDD) {
		pgCount = pgDD.options[pgDD.selectedIndex].value;
	}
	return pgCount;
} 
/**********************************************************************
************************ END THUMBS PER PAGE **************************
**********************************************************************/


/**********************************************************************
*************************** PAGE NAVIGATION ***************************
**********************************************************************/
function changePage(pgId) {
	var splt,pg;
	splt = pgId.split('_');
	pg = splt[1];
	pgNumActive = pg;
	prepAndSend('pagechange');
	return false;
}

function createPageLink(pn,curPg) {
	var pgLink,pgText;
  	if (pn == curPg) {
  		pgText=document.createTextNode(pn + ' ');
  		return pgText;
  	}
  	else {
	  	pgLink=document.createElement('a');
		pgText=document.createTextNode(pn);
		pgLink.appendChild(pgText);
		pgLink.setAttribute('href','#');
		pgLink.setAttribute('id','pgBar_'+pn);
		pgLink.style.margin = '0 6px 0 0';
		pgLink.onclick=function(){ changePage(this.id); return false; };
		return pgLink;
	}
}

function createPrevNext(pg,show,prevnext) {
	if (show) {
		var pnSpan,pnLink;
		pnLink = document.createElement('a');
		pnLink.style.width = '89px';
		pnLink.style.height = '22px';
		pnLink.setAttribute('href','#');
		if (prevnext == 'prev') pnLink.className = "linkPrevious";
		else pnLink.className = "linkNext";
		pnImg = document.createElement('img');
		if (prevnext == 'prev') pnImg.setAttribute('alt','Previous Page');
		else pnImg.setAttribute('alt','Next Page');
		pnImg.style.width = '89px';
		pnImg.style.height = '22px';
		pnImg.src = 'images/clearpixel.gif';
		//if (prevnext == 'prev') pnImg.src = 'images/button_previous.gif';
		//else pnImg.src = 'images/button_next.gif';
		pnLink.setAttribute('id','pgBar' + prevnext + '_' + pg);
		pnLink.appendChild(pnImg);
		pnLink.onclick=function(){ changePage(this.id); return false; }
		return pnLink;
	}
	else {
		var pnImg;
		pnImg = document.createElement('img');
		pnImg.style.width = '89px';
		pnImg.style.height = '22px';
		pnImg.src = 'images/clearpixel.gif';
		return pnImg;
	}
}

function updPaging(thumbsPerPage,curPg,totalRecs,rc) {
	/* Determine the number of pages to be accounted for in the paging bar - I'm basing the "current" page,
	number as well as the page number range, on the page count and page number that was passed in the original
	request rather than the current drop-down/paging bar values, since they might have changed. */
	if (thumbsPerPage == 'All') thumbsPerPage = totalRecs;
	var numPages = Math.ceil(totalRecs/thumbsPerPage);
	
	/* The page numbers will be made by looping from a low-end page number to a high-end page number, potentially
	with a hard-coded 1 and/or elipsis tacked on the beginning, or a hard-coded ellipsis and/or last page tacked
	on the end. The logic determines the dynamic page numbers for the middle of the paging bar first, and if the
	first page or last page are not accounted for within that range, then the tacking takes place. */
	
	/* The current page should be the one in the middle of 5 page numbers shown in the interior of the bar, so
	the low end of the 5 will default to two less than the current page number. For instance, if the current page
	is 24, the first number in the series of 5 will be 22, so the sequence of 5 will be 22 23 24 25 26. */
	var lowEnd = curPg - 2;
	/* If the current page is within 2 pages of the high end of the available pages, we need to just show the last
	5 pages, otherwise the sequence will display more page numbers than are available. */
	if (curPg > numPages - 2) lowEnd = numPages - 4;
	/* If the starting point for the sequence of 5 is less than 1, then we need to force it to begin at one,
	otherwise our displayed page numbers will start in negative numbers. */
	if (lowEnd <= 1) lowEnd = 1;
	/* Calculate the last number in the sequence of 5 from the starting number. */
	var highEnd = lowEnd + 4;
	/* In cases where there are fewer than 5 pages, the addition of 4 above could exceed that limit, so we'll
	again force the high end to equal the number of available pages. */
	if (highEnd >= numPages) highEnd = numPages;
	
	// Create Paging Bar HTML
	var pgP = $('pSortRight');
	if (!pgP) return false;
	removeChildren(pgP);
	/* Show "prev" button if we're not on the first page. */
	pgP.appendChild(createPrevNext((parseInt(curPg) - 1),(curPg > 1),'prev'));
	if (lowEnd > 0 && highEnd > 0) pgP.appendChild(document.createTextNode("\u0020\u0020\u0020page: ")); 
	if (lowEnd > 1) pgP.appendChild(createPageLink(1,curPg));
	if (lowEnd == 3) pgP.appendChild(createPageLink(2,curPg));
	if (lowEnd > 3) pgP.appendChild(document.createTextNode("\u2026 "));
	for (var i=lowEnd; i <= highEnd; i++) { pgP.appendChild(createPageLink(i,curPg)); }
	if (highEnd < (numPages-2)) pgP.appendChild(document.createTextNode("\u2026 "));
	if (highEnd == (numPages-2)) pgP.appendChild(createPageLink((numPages-1),curPg));
	if (highEnd < numPages) pgP.appendChild(createPageLink(numPages,curPg));
	/* Show "next" button if we're not on the first page. */
	pgP.appendChild(createPrevNext((parseInt(curPg) + 1),(curPg < numPages),'next'));
	//alert('Thumbs Per Page: ' + thumbsPerPage + ', Current Page: ' + curPg + ', Records Returned: ' + rc + ', Total Recordcount: ' + totalRecs + ', Num Pages: ' + numPages + ', lowEnd: ' + lowEnd + ', highEnd: ' + highEnd);
}
/**********************************************************************
************************ END PAGE NAVIGATION **************************
**********************************************************************/


/**********************************************************************
*********************** AJAX RESPONSE HANDLERS ************************
**********************************************************************/
function showDebug(txt,xcoord,ycoord,ht,divName) {
	var divObj = $(divName);
	if (divObj) {
		removeChildren(divObj);
		document.body.removeChild(divObj);
	}
	divNew = document.createElement('div');
	divNew.setAttribute('id',divName); 
	divNew.style.visibility = "visible";
	divNew.style.width = '300px';
	divNew.style.height = ht + 'px';
	divNew.style.position = 'absolute';
	divNew.style.fontSize = '10px';
	divNew.style.borderWidth = "1px";
	divNew.style.backgroundColor = "#ffffcc";
	divNew.style.left  = xcoord + "px";
	divNew.style.top   = ycoord + "px";
	divNew.style.overflow = 'scroll';
	divNew.innerHTML = txt;
	document.body.appendChild(divNew);
}

function parseResponse(rsp) {
	if (rsp && rsp.DATA && rsp.ERROR == '') {
		/* The data in ORIGREQ was stringified with JSON when it was originally sent to the server, and is 
		being returned in this response unchanged. Although the server response we're now processing was 
		itself a JSON string that was unpacked, the embedded ORIGREQ string needs to be unpacked separately. */
		//alert('returned origreq:\n' + rsp.DATA.ORIGREQ);
		if (rsp.AJAXDEBUG) showDebug('<h3>AJAX Debug:</h3>' + rsp.AJAXDEBUG,1,1,300,'divAJAXDebug');
		//if (rsp.DATA.ORIGREQ) showDebug('<h3>ORIGREQ:</h3>' + rsp.DATA.ORIGREQ,1,305,300,'divOrigReq');
		
		var o = eval('(' + rsp.DATA.ORIGREQ + ')');
		rsp.DATA.ORIGREQ = o;

		if (rsp.SOURCE == 'Cached') {
			/* We need to set up our page to match the look and feel that it had on the last visit, if indeed 
			we have stored info from the last visit to this thumbnail page in the Session. */
			setFacetSelections(o.fctelms);
			setSortSelection(o.sorter);
			setThumbsPerPage(o.pgcount);
		}
		
		updFacetCounts(rsp.DATA.FCTS);
		//alert(rsp.DATA.PRODAREA.RECORDCOUNT);
		if (rsp.DATA.PRODAREA.RECORDCOUNT) updThumbs(rsp.DATA.PRODAREA.html);
		else showNoResults();
		updPaging(o.pgcount,o.pagenum,rsp.DATA.PRODAREA.TOTALRECORDCOUNT,rsp.DATA.PRODAREA.RECORDCOUNT);
		if(typeof pageSpecificResponseActions == 'function') {
			pageSpecificResponseActions();
		}
	} 
	else {
		alert(rsp.ERROR);
	}
}

function handleError(rsp) {
	alert(rsp);
}
/**********************************************************************
********************* END AJAX RESPONSE HANDLERS **********************
**********************************************************************/


/**********************************************************************
****** AJAX OUTBOUND PAYLOAD STRUCTURER AND REQUEST MANAGEMENT ********
**********************************************************************/
function CheckURLOverride(act,urlvar,dflt) {
	var rtn = dflt;
	if (act == 'init') {
		x = getURLVar(urlvar);
		if (x.length) rtn = x;
	}
	return rtn;
}

function createPayload(act) {
	this.act = act;
	// Add the page-specific properties from the .cfm's JavaScript. 
	for (var prop in ajP) {	this[prop] = ajP[prop]; } //eval("this."+prop+"='"+ajP[prop]+"'");
		
	/* The following values are ascertained through looking at the DOM. During an init,
	these can be overridden using URL params. */
	this.sorter = CheckURLOverride(act,'srt',getSortVal());
	this.pgcount = CheckURLOverride(act,'pct',getPageCount());
	this.pagenum = CheckURLOverride(act,'pnm',pgNumActive);
	this.fctelms = bundleFacetVals();
	
	/* If we are passed a pid (product id) then the browser is requesting that we load
	whatever page of thumbnails holds that product. Since we don't know the page, we
	pass the pid along to the server so that display page can be determined there. */
	if (act == 'init') {
		var x = getURLVar('pid')
		if (x.length) this.pid = x;
	}
}

function sendPayload(pld) {
	//alert(JSON.stringify(pld));
	var payload = new Array();
	payload['thumb_page_params'] = JSON.stringify(pld);
	var url = 'ThumbAjaxHandler.cfm?timeStamp=' + new Date().getTime();
	HTTP.post(url,payload,parseResponse,handleError);
	return true;
}

function prepAndSend(act) {
	if (act != 'pagechange') pgNumActive = 1;
	var pldVal = new createPayload(act);
	if (act != 'pagechange') addFacetProgress();
	addProdAreaProgress();
	sendPayload(pldVal);
	return true;
}

/**********************************************************************
**** END AJAX OUTBOUND PAYLOAD STRUCTURER AND REQUEST MANAGEMENT ******
**********************************************************************/


/**********************************************************************
******************************** INIT *********************************
**********************************************************************/
function init() {
	ajP = new ajaxStartParams();
	asgnFacetHandlers();
	asgnSortHandler();
	asgnNumPerPageHandler();
	prepAndSend('init');
}
