navMargin = 105;		// nav margin
imageWidth = 250;		// width of each image in pixels
scrollTime = 200;		// time for each unit of scroll in milliseconds
currentLocation = 0;

$(document).ready(function(){
    scrollEvents();
    $('.close, .close a').click(function() {
        $('#intro').hide();
        return false;
    });
    $('#help a').click(function() {
        $('#intro').show();
        return false;
    });

	disableSelection($('.container').get(0));
});

$.address.change(function(event) {  
    clickHandler(event);  
});

function scrollEvents()
{
    $('#scrollLeft').unbind();
    $('#scrollLeft').repeatedclick(function() {
		scrollLeft();
    }, {
		duration: scrollTime,
		speed	: 1.0,
		min		: scrollTime
	});
	$('#scrollLeft').click(function() {return false;});

    $('#scrollRight').unbind();
    $('#scrollRight').repeatedclick(function() {
		scrollRight();
    }, {
		duration: scrollTime,
		speed	: 1.0,
		min		: scrollTime
    });
	$('#scrollRight').click(function() {return false;});
}

function scrollLeft()
{
	if ( currentLocation < navMargin ) {
		$('#grades').animate( { left : '+=' + imageWidth + 'px' }, scrollTime );
		currentLocation += imageWidth;
		if (currentLocation == navMargin )
			hover ("Left", "off");	
		hover("Right");
	}
}

function scrollRight()
{
	if ( currentLocation > maxSlide ) {
		$('#grades').animate( { left : '-=' + imageWidth + 'px' }, scrollTime );
		currentLocation -= imageWidth;
		if (currentLocation == maxSlide)
			hover ("Right", "off");	
		hover("Left");
	}
}
    
function clickHandler(event) {
    if (event.pathNames[0])
        trackGA(event);
    
    switch(event.pathNames[1])
    {
        case "Grades":
            loadGrades(event);
            break;
        default:
            loadCategories(event);
    }
}

function hover ( button, off ) {
    if (off)
    {
		if(!$.browser.msie)
		{
			$('#' + button).fadeTo(200, 0);
			$('#' + button).hide(); // without hide, mouseover turns mouse pointer to hand
		}
		else
			$('#' + button).hide();
    }
    else
    {
		$('#' + button).hover(
			 function(){$(this).attr({ src : 'images/button' + button + 'Lit.png' });},
			 function(){$(this).attr({ src : 'images/button' + button + 'Off.png' });}
		);
		if(!$.browser.msie)
		{
			$('#' + button).fadeTo(200, 1);
			$('#' + button).show();
		}
		else
			$('#' + button).show();
    }
}

function setEvents() {
    $('.container a:not(.scroll):not(.zoom):not(.close a):not(.open)').address();
    // todo: modify lightBox to use back-button
	$('.obverse, .reverse').lightBox();
}

function loadCategories(event) {
    var thisCategory = event.pathNames[0];
    var title;
    var coinfacts = '';

    if (thisCategory)
    {
		// todo: this bugs with URL hacking, fix (also causes post-error loading issue on IE)
		var c = $.grep(categories, function(cat, i) { return cat.id == thisCategory });
		$("#pictures1").html(buildCategoryHtml(c[0].subcategories, "Grades"));
		title = c[0].name;
		coinfacts = coinfactsLink(c[0].coinfacts, c[0].name);
	
		$('.categoryLink a').css('font-size','15px');
    }
    else
    {
        title = 'PCGS Photograde&trade; Online';
		$("#pictures1").html(buildCategoryHtml(categories));

//		$('.categoryLink a').css('font-size','19px');
		
		if ( !($.cookie('PhotogradeFirstRun') ) )
		{
		    $('#intro').show();
		    $.cookie('PhotogradeFirstRun', 'No', { expires: 365, path: '/' });
		}
		
    }

    $("#title").html(title);
    document.title = title.replace('&trade;', '');
    $("#coinfacts").html(coinfacts);
    $(".navbutton").hide();

    setEvents();
}

function buildCategoryHtml (categoryArray, action) {
    var out = '';

    $.each(categoryArray, function() {
		out += '<div class="category">';
		out += '<div class="categoryImage">';
		out += '<a href="#" rel="address:/' + this.id + (action ? '/' + action : '') +  '">';
		out += '<img src="' + path.thumb + this.image + '-o.jpg" alt="' + this.name + '" />';
		out += '</a>';
		out += '<a href="#" rel="address:/' + this.id + (action ? '/' + action : '') +  '">';
		out += '<img src="' + path.thumb + this.image + '-r.jpg" alt="' + this.name + '" />';
		out += '</a>';
		out += '</div>';
		out += '<div class="categoryLink">';
		out += '<a href="#" rel="address:/' + this.id + (action ? '/' + action : '') +  '">';

		// put the dates on a second line
		var index = this.name.lastIndexOf('(');
		var categoryName = this.name;
		if (index > -1)
		    categoryName = categoryName.substring(0, index-1) + '<br />' + categoryName.substring(index);
		     
		out += categoryName;
		out += '</a>';
		out += '</div>';
		out += '</div>';
    });

    return out;
}

function findSubcategory (id) {
    var c;
    $.each(categories, function() {
		if (this.subcategories.length > 0)
			c = $.grep(this.subcategories, function (cat, i) { return cat.id == id });
		if (c.length > 0)
			return false;
    });
    return c[0];
}

function loadGrades(event) {
    var out = '<div id="grades">';
    var thisCategory = findSubcategory(event.pathNames[0]);
    var gradeSet = thisCategory.grades;

	// precache the first images to show on screen
	var len = gradeSet.length;
	var cacheGradeSet = [gradeSet[len-5], gradeSet[len-4], gradeSet[len-3], gradeSet[len-6], gradeSet[len-2]];

	$.each(cacheGradeSet, function(i, val) {
		$('<img/>').attr('src', path.small + thisCategory.image + '-' + val + 'o.jpg');		
		$('<img/>').attr('src', path.small + thisCategory.image + '-' + val + 'r.jpg');		
	});

	// build the slider html
    $.each(gradeSet, function(i, val) {
		out += '<div class="grade" style="position: absolute; left: ' + i * imageWidth + 'px;">';
		out += '<a href="' + path.large + thisCategory.image + '-' + val + 'o.jpg"'; 
		out += ' class="zoom obverse" title="' + thisCategory.name + ' ' + gradeDesc(val) + '">';
		out += '<img src="' + path.small + thisCategory.image + '-' + val + 'o.jpg" />';  	
		out += '</a>';
		out += '<div>' + gradeDesc(val) + '</div>';
		out += '<a href="' + path.large + thisCategory.image + '-' + val + 'r.jpg"';
		out	+= ' class="zoom reverse" title="' + thisCategory.name + ' ' + gradeDesc(val) + '">';
		out += '<img src="' + path.small + thisCategory.image + '-' + val + 'r.jpg" />';  	
		out += '</a>';
		out += '</div>';
    });

    out += '</div>';

    maxSlide = -((gradeSet.length - 3) * imageWidth - navMargin);
    currentLocation = maxSlide + 2 * imageWidth;  // start window 2 from far right slide
    
    $('#pictures1').html(out);
    $('#grades').css( 'left', currentLocation + 'px' );
    hover('Left');
    hover('Right');
    $('.navbutton').show();
    $('#title').html(thisCategory.name);
    document.title = thisCategory.name;
    $('#coinfacts').html(coinfactsLink(thisCategory.coinfacts, thisCategory.name));

    setEvents();

    // todo:
    // * animation bugged when zoomed in chrome/safari
}

function coinfactsLink(coinfacts, title) {
    var link = '';
    if (typeof coinfacts != 'undefined') {
        link = '<a href="http://www.pcgscoinfacts.com/Hierarchy.aspx?c=' + coinfacts + '">View on PCGS CoinFacts</a>';
    }

    return link;
}

function trackGA(event)
{
    if (typeof pageTracker != 'undefined')
		pageTracker._trackPageview('/PhotoGrade' + event.path);
}

function disableSelection(target){

    if (typeof target.onselectstart!="undefined") //IE route
        target.onselectstart=function(){return false};

    else if (typeof target.style.MozUserSelect!="undefined") //Firefox route
        target.style.MozUserSelect="none";

    else //All other route (ie: Opera)
        target.onmousedown=function(){return false};

	target.ondragstart=function(){return false}; 
   // target.style.cursor = "default"
}


