var xsort = {};
var tilesinsort = 6;
var presenttile = 0;
var presenttop = 0;
var presentheight = 0;

function nbsort(sortelement,displaytiles,wrapper) {
	this.borderheight = 1;
	this.displaytiles = displaytiles;
	this.tiles = sortelement.length;
	this.presentview = 0;
	/*set number of views*/
	if (this.tiles > 0){
		this.views = Math.ceil(this.tiles/this.displaytiles);
	} else {this.views = 0;}	
	/*determine the height of each view*/
	if (this.views > 0){
	var elementptr = 0;
	var viewptr = 0;
	var tilecount = 0;
	this.viewheight = new Array();
	this.viewtop = new Array();
	while (elementptr < this.tiles){
		this.viewheight[viewptr] = 0;	
		while ((tilecount < this.displaytiles) && (elementptr < this.tiles)){
			this.viewheight[viewptr] = this.viewheight[viewptr]+(sortelement[elementptr].scrollHeight+this.borderheight)*1;
			if (elementptr < (this.tiles-1)){
			this.viewtop[viewptr] = sortelement[elementptr+1].offsetTop*1;}
			else { //add a temporary element to list to find the offsetTop of the next element
			var templi = document.createElement('li');
			$(sortelement[elementptr].parentNode).append(templi);
			this.viewtop[viewptr] = sortelement[elementptr].parentNode.childNodes[elementptr+1].offsetTop*1;
			$(sortelement[elementptr].parentNode.childNodes[elementptr+1]).remove();
			}
			tilecount++;
			elementptr++;
		}
		tilecount = 0;
		viewptr++;
	}
//	$('li.vasortli').css('display','inline');
	$(wrapper).css('height',this.viewtop[0]+'px');
	}	
};

nbsort.prototype.resetview = function (){
	this.presentview = 0;
	return this.presentview;
}

nbsort.prototype.getdistance = function(startptr){
	var x = 0;
	if (startptr >= 0) {
		x = this.viewtop[startptr];
	} 
	return x;
}

nbsort.prototype.getheight = function(startptr){
	var x = 0;
	x = this.viewheight[startptr];
	return x;
}

nbsort.prototype.setpresentview = function(startptr){
	this.presentview = startptr;
}

nbsort.prototype.presentheight = function(){
	var x = 0;
	if (this.presentview > 0){
		x = this.viewtop[this.presentview] - this.viewtop[this.presentview-1];
	} else {
	x = this.viewtop[this.presentview];}
	return x;
}

nbsort.prototype.priorheight = function(){
	var x = 0;
	if (this.presentview-1 > 0){
		x = this.viewtop[this.presentview-1] - this.viewtop[this.presentview-2];
	} else {
	x = this.viewtop[this.presentview-1];}
	return x;
}

nbsort.prototype.locatestart = function(startpositiongoal){
	var x=0;
	while ((startpositiongoal >= this.viewtop[x]) && (x+1 != this.views)){
		x++;
	}
	return x;
}

nbsort.prototype.viewtopget = function(){
	return this.viewtop[this.presentview];
}

nbsort.prototype.incrementview = function(){
	var x = 0;
	if (this.presentview < (this.views-1)){
		this.presentview++;}
	x = this.presentheight();
	return x;
}

nbsort.prototype.decrementview = function(){
	var x=0;
	if (this.presentview > 0){
	this.presentview--;
	}
	x = this.presentheight();
	return x;
}

function activatelike(loc){
$('#fb'+loc).show();
}

function hidelike(loc){
$('#'+loc).hide();
}

/**
 * jQuery.fn.sortElements
 * --------------
 * @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 quickrank(x){
	if (x.firstChild.href){
	var s = x.firstChild.href.lastIndexOf('/');
	var n = x.firstChild.href.substring(s+1);
	n = n.replace('.','');
	var p = dmsrt[n];
	return (p);
	}
}

function quickrecent(x){
	if (x.firstChild.href){
	var s = x.firstChild.href.lastIndexOf('/');
	var n = x.firstChild.href.substring(s+1);
	n = n.replace('.','');
	var p = recsort[n];
	return (p);
	}
}

function getrank(x){
	if (x.firstChild.firstChild.href){
	var s = x.firstChild.firstChild.href.lastIndexOf('/');
	var n = x.firstChild.firstChild.href.substring(s+1);
	n = n.replace('.','');
	var p = dmsrt[n];
	return (p);
	}
}

function getrecent(x){
	if (x.firstChild.firstChild.href){
	var s = x.firstChild.firstChild.href.lastIndexOf('/');
	var n = x.firstChild.firstChild.href.substring(s+1);
	n = n.replace('.','');
	var p = recsort[n];
	return (p);
	}
}

function quicksort(choice){
	$('li.vapagesort').sortElements(function(a,b) {
		switch(choice) {
			case 'r':
			return quickrecent(a) < quickrecent(b) ? 1 : -1;
			break;
			case 'p':
			return quickrank(a) > quickrank(b) ? 1 : -1;
			break;
			case 'a':
			return $(a).text() > $(b).text() ? 1 : -1;
			break;
			default:
				break;
			}
	});
}


function dosort(choice){
	$('li.vasortli').sortElements(function(a,b) {
		switch(choice) {
			case 'r':
			return getrecent(a) < getrecent(b) ? 1 : -1;
			break;
			case 'p':
			return getrank(a) > getrank(b) ? 1 : -1;
			break;
			case 'a':
			return $(a).text() > $(b).text() ? 1 : -1;
			break;
			default:
				break;
			}
	});
	$('ul.navbarul').css('top','0px');	
	var sortlist = $('li.vasortli');
	xsort = new nbsort(sortlist,tilesinsort,'#navbarwrap');
}

function slidefoot(navpos,lastnav){
	$('.footnavmenu').removeClass('boldit');
	var navwidth = $('#footerrotatewrap').width();
	var moveit = navwidth * navpos * -1;
	$('#footerpos').css('left',moveit);
	$('#footnav'+navpos).addClass('boldit');
}

function clearbuttons(){
	$('.navrbbutton').removeClass('boldbutton');
}

function textclear(){
	$('.textnavs').removeClass('currenttext');
}

function shownav(){
	$(this).find('ul.navmenu').css('visibility','visible');	
}

function hidenav(){
	$(this).find('ul.navmenu').css('visibility','hidden');
}

function hidemovie(){
	$("#bannermovie").hide();
}

function changeimg(){
	var x = $('#mainimg')[0].innerHTML;
	var z = $('#chgimgbutton')[0].innerHTML;
	var exp = /\/tshirts\//;
	var replace = /\/tshirtmodels\//;
	var description = /See on Shirt/;
	var descriptionreplace = /See Design/;
	var replacedescription = "See Design";
	var originaldescription = "See on Shirt"; 
	var exp2 = /tshirt.gif/;
	var replace2 = /model.jpg/;
	var replacestring = "/tshirtmodels/";
	var originalstring = "/tshirts/";
	var replaceend = "model.jpg";
	var originalend = "tshirt.gif";
	var result = x.match(exp);
	var resultmodel = x.match(replace);
	if (result != null) {
	x = x.replace(exp2,replaceend);
	$('#mainimg')[0].innerHTML=	x.replace(exp,replacestring);
	z = z.replace(description,replacedescription);
	$('#chgimgbutton')[0].innerHTML = z;
	} else { if (resultmodel != null) {
	x = x.replace(replace2,originalend);
	$('#mainimg')[0].innerHTML=	x.replace(replace,originalstring);
	z= z.replace(descriptionreplace,originaldescription);
	$('#chgimgbutton')[0].innerHTML = z;
	}}
}

function showskin(skinspace){
	$('#'+skinspace)[0].style.cssText='visibility:visible;';
}

function hideskin(skinspace){
	$('#'+skinspace)[0].style.cssText='visibility:hidden;';
}

function setsidenav(presentpage){
	var h = $('ul.navbarul').height();
	var p = $('ul.navbarul').position();
	var sortpositiongoal = $('#'+presentpage)[0].offsetTop;
	/*
	Find next greatest height in sort order.  
	move right nav to that position
	*/
	var startptr = xsort.locatestart(sortpositiongoal);
	var movedistance = xsort.getdistance(startptr-1);
	var movestring = "-="+movedistance+"px";
	var moveup = xsort.getheight(startptr);
	if ((Math.abs(p.top) + presentheight) < h) {
		$('ul.navbarul').animate({"top": movestring}, "fast");
		$('#navbarwrap').css('height',moveup+'px');	
	}
	xsort.setpresentview(startptr); //make
}

$(document).ready(function(){

$('li.navpulldown').bind('mouseover',shownav);
$('li.navpulldown').bind('mouseout',hidenav);

if($('.share').length){
	var fade;
	$('.shbutton').click(function(e){
		e.stopPropagation();
		e.preventDefault();
		var shareMenu = $(e.target).parent().find('.sharebox');
		shareMenu.fadeIn(100);
		shareMenu.bind('clickoutside',function() {shareMenu.hide();});
	});
	$('.sharebox .sharetop span').click(function(e){
		e.stopPropagation();
		e.preventDefault();
		$(e.target).parents('.sharebox').hide();
	});
	$('.embutton').click(function(e){
		e.stopPropagation();
		e.preventDefault();
		var emailMenu = $(e.target).parent().parent().parent().parent().find('.emailbox');
		emailMenu.fadeIn(100);
		emailMenu.bind('clickoutside',function() {emailMenu.hide();});	
	});
	$('.emailbox .sharetop span').click(function(e){
		e.stopPropagation();
		e.preventDefault();
		$(e.target).parents('.emailbox').hide();
	});

}



if ($('li.vasortli').length > 0){
	var sortlist = $('li.vasortli');
	xsort = new nbsort(sortlist,tilesinsort,'#navbarwrap');
	dosort('p');
	clearbuttons();
	$('#popularsort').addClass('boldbutton');
}

$("#demproductlist li:last").addClass("last");

$("#popularvasort").click(function(){
	quicksort('p');
	clearbuttons();
	$(this).addClass('boldbutton');
});

$("#movieshow").click(function(){
	$("#bannermovie").show();
});



$("#recentvasort").click(function(){
	quicksort('r');
	clearbuttons();
	$(this).addClass('boldbutton');
});

$("#alphavasort").click(function(){
	quicksort('a');
	clearbuttons();
	$(this).addClass('boldbutton');
});


$("#popularsort").click(function(){
	dosort('p');
	clearbuttons();
	$(this).addClass('boldbutton');
});

$("#recentsort").click(function(){
	dosort('r');
	clearbuttons();
	$(this).addClass('boldbutton');
});

$("#alphasort").click(function(){
	dosort('a');
	clearbuttons();
	$(this).addClass('boldbutton');	
});

$("#movedown").click(function(){
	var x = $('ul.navbarul');
	var h = $('ul.navbarul').height();
	var p = $('ul.navbarul').position();
	var presentheight = xsort.presentheight();
	var viewtop = xsort.viewtopget();
	var moveup = xsort.incrementview();
	var movestring = "-="+presentheight+"px";
	if ((Math.abs(p.top) + presentheight) < h) {
	$('ul.navbarul').animate({"top": movestring}, "fast");
	$('#navbarwrap').css('height',moveup+'px');
	}
});
$("#moveup").click(function(){
	var p = $('ul.navbarul').position();
	var priorheight = xsort.priorheight();
	var movestring = "+="+priorheight+"px";
	var movedown = xsort.decrementview();

	if (p.top + priorheight < 0) {
	$('ul.navbarul').animate({"top": movestring}, "fast");
	$('#navbarwrap').css('height',movedown+'px');	
	} else {$('ul.navbarul').css('top','0px');}
});

$("#revealskins").click(function(){
	$('#'+skinspace)[0].style.cssText='visibility:visible;';
});

});

