// Drillpine.biz - Sorted Product Support V3.00 jQuery version
var bSortInitalised = false;

/**
 * jQuery.fn.sortElements - http://james.padolsey.com/javascript/sorting-elements-with-jquery/
 * --------------
 * @param Function comparator:
 *   Exactly the same behaviour as [1,2,3].sort(comparator)
 *   
 * @param Function getSortable
 *   A function that should return the element that is
 *   to be sorted. The comparator will run on the
 *   current collection, but you may want the actual
 *   resulting sort to occur on a parent or another
 *   associated element.
 *   
 *   E.g. $('td').sortElements(comparator, function(){
 *      return this.parentNode; 
 *   })
 *   
 *   The <td>'s parent (<tr>) will be sorted instead
 *   of the <td> itself.
 */
jQuery.fn.sortElements = (function(){
 
    var sort = [].sort;
 
    return function(comparator, getSortable) {
	getSortable = getSortable || function(){return this;};
	var placements = this.map(function(){
		var sortElement = getSortable.call(this),
			parentNode = sortElement.parentNode,
				// Since the element itself will change position, we have
				// to have some way of storing its original position in
				// the DOM. The easiest way is to have a 'flag' node:
				nextSibling = parentNode.insertBefore(
					document.createTextNode(''),
					sortElement.nextSibling
					);
		return function() {
			if (parentNode === this) 
				{
				throw new Error("You can't sort elements if any one is a descendant of another.");
				}
			// Insert before flag:
			parentNode.insertBefore(this, nextSibling);
			// Remove flag:
			parentNode.removeChild(nextSibling);
			};
		});
	return sort.call(this, comparator).each(function(i){placements[i].call(getSortable.call(this));});
};
})();

function sortbyid(spanid, seqtype){	// sort defined spans depending on sequence
	switch (seqtype)
		{
		case 'lowhigh' : $("span[id^='" + spanid + "']").sortElements(function(a,b){return $(a).attr('price').replace(/[^\d\.]/g,'') - $(b).attr('price').replace(/[^\d\.]/g,'')}); break;
		case 'highlow' : $("span[id^='" + spanid + "']").sortElements(function(a,b){return $(b).attr('price').replace(/[^\d\.]/g,'') - $(a).attr('price').replace(/[^\d\.]/g,'')}); break;
		case 'default' : $("span[id^='" + spanid + "']").sortElements(function(a,b){return $(a).attr('seq') - $(b).attr('seq') }); break;
		case 'alpha'   : $("span[id^='" + spanid + "']").sortElements(function(a,b){return $(a).attr('pname') <= $(b).attr('pname') ? -1 : 1;}); break;
		case 'reverse' : $("span[id^='" + spanid + "']").sortElements(function(a,b){return $(b).attr('pname') <= $(a).attr('pname') ? -1 : 1;}); break;
		}
}

// Product Related
var lastsorttype = 'default';
var bReadyToSort = false;
function reseq(seqtype, gotoanchor){			// resequence products
	if ( ! (bReadyToSort || bPageIsLoaded) )
		{
		alert('Please wait until the page has fully loaded. (PROD)');
		return false;
		}
	sortbyid('sortline_', seqtype);
	lastsorttype = seqtype;
	setCookie('SORTTYPE', lastsorttype);
	showsorttype(lastsorttype, 'sortdropdown', 'sortlink', 'sortactive', 'sortinactive');
	if ( gotoanchor && location.hash ) scrolltoanchor(location.hash);	// Product Page just loaded and Anchor so we need to reposition
	//  Some Drillpine add-ons may need reactivated after the DOM has been fiddled with - add code here
	return false;
}

//  Search Results Related
var searchlastsorttype = 'default';
var bSearchReadyToSort = false;
function searchreseq(seqtype){			// resequence search results
	if ( ! (bSearchReadyToSort || bPageIsLoaded) )
		{
		alert('Please wait until the page has fully loaded. (SRC)');
		return false;
		}
	sortbyid('searchsortline_', seqtype);
	searchlastsorttype = seqtype;
	setCookie('SEARCHSORTTYPE', searchlastsorttype);
	showsorttype(searchlastsorttype, 'searchsortdropdown', 'searchsortlink', 'searchsortactive', 'searchsortinactive');
	return false;
}

// Section Related
var sectlastsorttype = 'default';
var bSectReadyToSort = false;
function sectionseq(seqtype){			// resequence Sections
	if ( ! (bSectReadyToSort || bPageIsLoaded) )
		{
		alert('Please wait until the page has fully loaded. (SECT)');
		return false;
		}
	sortbyid('sectionline_', seqtype);
	sectlastsorttype = seqtype;
	setCookie('SECTSORTTYPE', sectlastsorttype);
	showsorttype(sectlastsorttype, 'sectionsortdropdown', 'sectsortlink', 'sectsortactive', 'sectsortinactive');
	return false;
}

// General code
function showsorttype(sorttype, ddname, linkname, activeclass, inactiveclass){		// highlight the type of sort that's currently in use
	$("select[name='" + ddname + "']").val(sorttype);	// drop downs
	$("input[name='" + linkname + "']").each(function(idx){$(this).attr('class', ($(this).attr('id') == sorttype) ?  activeclass : inactiveclass) });	// buttons
	$("a[name='" + linkname + "']").each(function(idx){$(this).attr('class', ($(this).attr('id') == sorttype) ?  activeclass : inactiveclass) });		// a tags

}

function hidetagswithid(tag, id){	// hide all tags with ID
	$(tag + '#' + id).hide();
}

function scrolltoanchor(anc){		// reposition to display anchor
	anc = anc.replace(/.*\#/,'');		// Search highlight passes duplicate anchors - lose one
	$("a[name='" + anc + "']").get(0).scrollIntoView(true);
}

function sortinit(){				// called when DOM is loaded
	if (arguments.callee.done) return;
	arguments.callee.done = true;
	bSortInitialised = true;
	// Products
	if ( $('#sortwidget')[0] ) 
		{
		bReadyToSort = true;
		lastsorttype = getCookie('SORTTYPE');
		if ( lastsorttype == null ) lastsorttype = 'default';
		setCookie('SORTTYPE', lastsorttype);
		showsorttype(lastsorttype, 'sortdropdown', 'sortlink', 'sortactive', 'sortinactive');
		if ( lastsorttype != 'default' ) 
			{
			reseq(lastsorttype, true);
			}
		}	
	// Search Results
	if ( $('#searchsortwidget')[0] )
		{
		bSearchReadyToSort = true;
		searchlastsorttype = getCookie('SEARCHSORTTYPE');
		if ( searchlastsorttype == null ) searchlastsorttype = 'default';
		setCookie('SEARCHSORTTYPE', searchlastsorttype);
		showsorttype(searchlastsorttype, 'searchsortdropdown', 'searchsortlink', 'searchsortactive', 'searchsortinactive');
		if ( searchlastsorttype != 'default' ) 
			{
			searchreseq(searchlastsorttype);
			}
		}	
	// Sections
	if ( $('#sectsortwidget')[0] ) 
		{
		// check for no prices available and hide buttons if so	
		var rtot = 0;	
		$("span[id^='sectionline_']").each(function(i){var price = $(this).attr('price');rtot += (price != null) ? price - 0 : 0;  });
		if ( rtot == 0 )
			{
			if ( SectionSortLinksFinalOnly )					// do we only show links on final Sections
				{
				hidetagswithid('span', 'sectsortwidget');			// hide all sort widgets
				}
			else
				{	
				hidetagswithid('span', 'sectpricelinks');			// remove button or text price links
				$("#sectionsortdropdown option[value='lowhigh']").remove();	// remove price related options
				$("#sectionsortdropdown option[value='highlow']").remove();	// remove price related options
				}	
			}			
		bSectReadyToSort = true;
		sectlastsorttype = getCookie('SECTSORTTYPE');
		if ( sectlastsorttype == null ) sectlastsorttype = 'default';
		setCookie('SECTSORTTYPE', sectlastsorttype);
		showsorttype(sectlastsorttype, 'sectionsortdropdown', 'sectsortlink', 'sectsortactive', 'sectsortinactive');
		// only resequence if button showing and we've a non default sequence		
		if ( $('#sectsortwidget').is(':visible') && (sectlastsorttype != 'default') ) 
			{
			sectionseq(sectlastsorttype);
			}
		}
}

function onloadsortinit(){	// optionally called on onload
	if ( ! bSortInitalised ) sortinit();				// only init if it's not already run
}

$(document).ready(function() {onloadsortinit() });

