/* console.log fix */
if (typeof console == "undefined" || typeof console.log == "undefined") var console = { log: function() {} }; 

/* View more photo */
//Show More Photo

/* watermark */
function resetWatermarks()
{
    $('.searchBox input').each(function () {
        var txt = $(this).attr('placeholder');
        if (txt) {
            $(this).watermark(txt);
        }
    });
}

$(resetWatermarks);

/* utility nav hovers */
$(function () {
    var grey = 0.5;
    $('#utilityNav a').each(function () {
        var a = $(this);
        a.css('opacity', grey);
        a.hover(function () {
            a.stop(true, true);
            a.animate({ opacity: 1 }, 300);
        },
        function () {
            a.animate({ opacity: grey }, 200);
        });
    });

});

$(function () {
	var footerBg = $('#footerBg');
	
    footerBg.css('opacity', 0).animate({ 'opacity': 0.8 }, 1000);

    $('#footer-holder')
		.mouseenter(function () {
			footerBg
				.stop(true, true)
				.animate({ opacity: 1 }, 400);
			})
		.mouseleave(function () {
			footerBg
				.stop(true, true)
				.animate({ opacity: 0.8 }, 400);
			});
});

/* grid */
var videoOverlayImg = $('<img class="videoOverlay" src="/extension/qsdcshoes/design/dcshoes/images/overlayVideoLargeTop.png" />');

$('.largeContentRow .featured.videoContent').each(function () {

	$(this).find('.featuredImage').css('opacity', 0.2);
	$(this).prepend(videoOverlayImg.clone());
	$(this).hover(
		function () {
			$(this)
				.find('.featuredImage')
				.stop(true, true)
	            .animate({ 'opacity': 1 }, 150);
		},
		function() {
			$(this).find('.featuredImage').animate({ 'opacity': 0.2 }, 150);
		});
});

var videoOverlayImgSmall = $('<img class="videoOverlaySmall" src="/extension/qsdcshoes/design/dcshoes/images/overlayVideoThumb.png" />');

$('.smallContentRow .featured.videoContent').each(function () {
    $(this).find('.featuredImage').css('opacity', 0.2);
    $(this).prepend(videoOverlayImgSmall.clone());

    $(this).hover(
		function () {
	        $(this).find('.featuredImage')
	        .stop(true, true)
	        .animate({ 'opacity': 1 }, 150);
	    },
	    function () {
	        $(this).find('.featuredImage').animate({ 'opacity': 0.2 }, 150);
	    }
	);
});

var hoverTimeout;
$('body')
	.not('.IE7')
	.not('.IE8')
	.not('.IE6')
	.find('#products a').hover(
		function () {
			clearTimeout(hoverTimeout);
			var _self = this;
			$('#products a').each(function () {
				$(this).stop(true, true);
				if (_self === this) {
		             $(this).animate({ 'opacity': 1 }, 250);
		             return;
				}
				$(this).animate({ 'opacity': 0.4 }, 250);
			});
		},
		function () {
			hoverTimeout = setTimeout(function () {
				$('#products a').animate({ 'opacity': 1 }, 250);
			}, 250);
		}
	);

var results;
var defaultOffset = 6;
var lastOffset = 0;
var SearchText = "";
var subtreeArray = null;
var resultLimit = '';

function viewMoreButtonClick() {
	if (resultsLoading) return;

	var loading = $('<div class="loading">LOADING</div>');
	$('#results').append(loading);
	resultsLoading = true;
	offset = defaultOffset + lastOffset;
	setTimeout(function () {
	    //Fake delay, use this function as the ajax callback:
	    viewMoreAjaxSuccess('response', true);
		// Cufon refresh CTA on callouts
		Cufon.replace('.calloutRolloverCTA span',{hover: true});
		/*apl*/
		 getSearchResults(url, SearchText, offset, excludedObjects, includedClasses, view, subtreeArray, resultLimit);
	}, 500);

}
	
function sortOptionButtonClick (sortBy) {
	if (resultsLoading) return;
    var loading = $('<div class="loading">LOADING</div>');
    $('#results').append(loading);
    resultsLoading = true;
    setTimeout(function () {
        //Fake delay, use this function as the ajax callback:
        viewMoreAjaxSuccess('response', false);
    }, 2500);
}

//on view more ajax success
function viewMoreAjaxSuccess( response, append ) {
    resultsLoading = false;
    $('#results').find('.loading').remove();
    //Replace results with actual ajax result
       //var results = $(testingHTML);
		var results = $(response);
	if ( append ) {
		$('#results').append(results);
	} else {
		$('#results').html(results);
	}
    
    var els = results.find('.searchResult');
    // $(window).scrollTop($(document.body).height());
    els.css('opacity', 0);
    var elsToAnimate = -1;
    var totalEls = els.length;
    var i = els.length;
    var body = $(document.body);
    var newCSS = { 'opacity': 1 };
    var isIE = (body.hasClass('IE6') || body.hasClass('IE7') || body.hasClass('IE8'));
    if (isIE) {
        els.css(newCSS);
    }
    else {
        while (i--) {
            els.eq(i).delay(i * 75).animate(newCSS, 250);
        }
    }
	$(document).trigger('grid-loaded');
	FB.XFBML.parse();    return false;
}


var testingHTML = $('#results').html();
var results = $(testingHTML);
var resultsLoading = false;

$(function () {
	testingHTML = $('#results').html();
    results = $(testingHTML);
    resultsLoading = false;
	$('.resultsMoreButton').click(function (ev) {
		viewMoreButtonClick();
		return false;
		
	});
	$('#motoNews').find('.moreBtn').click(function (ev) {
		viewMoreButtonClick();
		return false;
		
	});	
	$('#searchResults .sortOptions a').click(function ( ev ) {
		$('#searchResults .sortOptions a').removeClass('active');
		$(this).addClass('active');
		var sortBy = $(this).attr('href').replace('#', '');
		sortOptionButtonClick(sortBy);
		return false;
	});
});

/*apl*/
function getSearchResults(url, SearchText, offset, excludedObjects,includedClasses, view, subtreeArray, resultLimit){
	lastOffset = offset;
	$.ajax({
		url:url,
		context: document.body,
		type: "POST",
		data: {SearchText: SearchText, Offset: offset, ExcludedItems:excludedObjects, IncludedClasses:includedClasses, View:view, SubTreeArray:subtreeArray, ResultLimit:resultLimit},
		success: function(data){
			if($('#results .contentBoxHeader').text() == 'No more results'){
				return;
			}
			viewMoreAjaxSuccess(data, true);							
		}
	});
}

function grayscale(image, bPlaceImage) {
	var myCanvas=document.createElement("canvas"),
		myCanvasContext = myCanvas.getContext("2d"),
		imgWidth=image.width,
		imgHeight=image.height,
		imageData;
		
	// You'll get some string error if you fail to specify the dimensions
	myCanvas.width = imgWidth;
	myCanvas.height = imgHeight;
	//  alert(imgWidth);
	myCanvasContext.drawImage(image,0,0);

	// The getImageData() function cannot be called if the image is not from the same domain.
	// You'll get security error
	imageData=myCanvasContext.getImageData(0,0, imgWidth, imgHeight);

	for (i=0; i<imageData.height; i++) {
		for (j=0; j<imageData.width; j++) {
			var index=(i*4)*imageData.width+(j*4),
				red=imageData.data[index],
				green=imageData.data[index+1],
				blue=imageData.data[index+2],
				alpha=imageData.data[index+3],
				average= (red+green+blue)/3;

				imageData.data[index]=average;
				imageData.data[index+1]=average;
				imageData.data[index+2]=average;
				imageData.data[index+3]=alpha;
		}
	}

	myCanvasContext.putImageData(imageData,0,0,0,0, imageData.width, imageData.height);

	if (bPlaceImage) {
		var myDiv=document.createElement("div");
		myDiv.appendChild(myCanvas);
		image.parentNode.appendChild(myCanvas);//, image);
	}

	return myCanvas.toDataURL('image/jpg');
}

// adds labels to atheletes in the drop down navigation
// fires on $(document).ready()
var makeLabel = function(container) {
		var navItem = $(container).find('li a img');

		$(navItem).each(function() {
			var labelText = $(this).attr('title'),
				labelContainer = $(this).parent(),
				chunks = labelText.split(" ");

			$('<div class="nameLabel"><span class="name">' + chunks.shift() + '<br /> ' + chunks.join(' ') + '</span></div>').appendTo(labelContainer);
		});
};

var galleryGrayScale = function(){
	
	// make name labels for athletes grid
	makeLabel('.tabContainer');

	if($('.socialShareWidget').length > 0) {
		$('.socialShareWidget').socialShare();
	}
	
	var timer;
	var homeBucketsActive = false;

	$('#homeBuckets').show();
	
	$('.callout').mouseenter( function() {
		var callout = $(this);

		timer = setTimeout(function() {
			if( homeBucketsActive === false ) {
				DCSHOES.GridBuilder.bucketHover('removeClass', 'fadeOut', callout);
			}

			if($('html').hasClass('canvas')) {
				DCSHOES.GridBuilder.faderize(callout, '1');
			} else {
				callout.find(".calloutHover").show();
			}

			// if the grid is expanded don't do anything
			if($('#homeBuckets').find('.moreBtnWrap').hasClass('expanded')) {
				return;
			}

			//callout.find(".featuredType").hide();
			
			homeBucketsActive = true;


		}, 200);
	}).mouseleave(function() {
		
		callout = $(this);
		
		clearTimeout(timer);

		if( homeBucketsActive === true ) {
			DCSHOES.GridBuilder.bucketHover('addClass', 'fadeIn', callout);
		}

		if($('html').hasClass('canvas')) {
			DCSHOES.GridBuilder.faderize(callout, '0.01');
		} else {
			$(this).find(".calloutHover").hide();
		}
		
		homeBucketsActive = false;

	});
	
	$("#homeBuckets .callout:lt(3)").addClass("topRow");
	$("#homeBuckets .callout:gt(2)").addClass("bottomRow");
	
	// IE
	$('#proTeamGrid, #amateurTeamGrid, #globalProTeamGrid, #nationalProTeamGrid, #globalAmateurTeamGrid, #europeanTeamGrid, #nationalTeamGrid').find('li a img').addClass('greyScale');
	$('.calloutImg').find('img').addClass('greyScale');
	
	if($('html').attr('class').indexOf('IE') < 0) {
		$('.greyScale').each(function() {
			var img = $(this);
			// Browsers that support canvas
			var src = img.attr('src');
			//if(src.indexOf('//' + window.location.hostname) == -1) {
			//	src = src.replace('//', '');
			//	var newSrc = src.substr(src.indexOf('/'), src.length);
			//	img.attr('src', newSrc);
			//}
			img.bind('load', function() {
				if($(this).parent().find('canvas').length === 0) {
					try {
						grayscale(this, true);
					} catch(e) {
						console.log('Error while filtering image:', e);
					}
				}
			});
		});
	}


	//Refresh XFBML - causes home page to blow up
	// if(typeof window['FB'] !== 'undefined') {
		// FB.XFBML.parse();
	// }
	
	// black and white roll over toggle for athlete panel
	//.callout, #proTeamGrid li a, #amateurTeamGrid li a,
	$('.callout, .grid6 li a, #proTeamGrid li a, #amateurTeamGrid li a, #globalProTeamGrid li a, #nationalProTeamGrid li a, #globalAmateurTeamGrid li a, #europeanTeamGrid li a, #nationalTeamGrid li a').mouseenter(function() {
		var originalImage = $(this).find('img'),
			canvas = $(this).find('canvas');

		originalImage.removeClass('greyScale');

		if(canvas.parent().hasClass('cufon')) {
			return;
		}
		
		canvas.hide();

	}).mouseleave(function() {
		var originalImage = $(this).find('img'),
			canvas = $(this).find('canvas');

		originalImage.addClass('greyScale');
		canvas.show();
	});

};

// equalize heights for the site map columns
$.fn.equalizeHeights = function(){
  return this.height( Math.max.apply(this, $(this).map(function(i,e){ return $(e).height(); }).get() ) );
};

$(document).ready(function() {
	galleryGrayScale();

	// for .grid6 hoverbar
	$('.calloutHover').mouseenter(function() {
		$(this).prev('.calloutImg').find('canvas').hide();
	});

	$('body').removeClass('image-loading');
	$('#site-map').find('.nav-main').equalizeHeights();

	$('.linkColumn').last('ul').addClass('last-child');

	// For Street Leauge and Shop League Micro Sites
	$('#autograph-social, #video-social').find('.facebook-share').click(function () {
		var href = window.location.href;
		window.open ("http://www.facebook.com/share.php?u=" + href , "share", "width=600, height=450");
		return false;
	});

	$('#autograph-social, #video-social').find('.twitter-share').click(function () {
		var href = window.location.href;

		window.open ("http://twitter.com/share?text=DC Shoes Street League &url=" + href, "share", "width=500, height=400");
		return false;
	});
	
	$('#autograph-social, #video-social').find('.email-share').click(function () {
		var href = window.location.href,
			shareText = "Street League";

		ShareModal.open(href, href, shareText, null, null, null);
		return false;
	});

	$('#buttons-container img[alt="Latest News"]').click(function() {
		var feedLocation = $('#motoNews').offset();
		$('html, body').animate({
			scrollTop: feedLocation.top
		});
		return false;
	});

});

