function IE(){return (jQuery.browser.msie)}
function IE6(){return (jQuery.browser.msie  && (Math.floor(jQuery.browser.version) == 6))}
function Opera(){return (jQuery.browser.opera)}

function getFullHeight(el)
{
	return el.height() + (parseInt(el.css('paddingTop'))||0) + (parseInt(el.css('paddingBottom'))||0) + (parseInt(el.css('borderTopWidth'))||0) + (parseInt(el.css('borderBottomWidth'))||0);
}

function getInnerWidth(el)
{
	return el.width() + (parseInt(el.css('paddingLeft'))||0) + (parseInt(el.css('paddingRight'))||0);
}
function getInnerHeight(el)
{
	return el.height() + (parseInt(el.css('paddingTop'))||0) + (parseInt(el.css('paddingBottom'))||0);
}


function initMainNav()
{
	jQuery('#MainNav>ul')
		.superfish({autoArrows: false });
}


function replaceSubmitButton(wrapper, cssClass)
{
	var submitBtn = wrapper.find('input:submit');
	var submitLink = jQuery('<a href="#" class="' + cssClass + '"><span>' + submitBtn.val() + '</span></a>');
	submitBtn.replaceWith(submitLink);
	submitLink
		.click(function()
				{
					var form = jQuery(this).parents('form');
					form.submit();
					return false;
				})
}

function replaceSubmitButtons()
{
	replaceSubmitButton(jQuery('form[name=Register]'), 'LinkButton');
	replaceSubmitButton(jQuery('form[name=SendCreativeReuse]'), 'LinkButton');
}

function resizeFeaturedItemsCols()
{
	var wrapper = jQuery('ul.FeaturedItemsList');
	if(wrapper.size() > 0)
	{
		var maxHeight = Math.max(
					 	wrapper.find('>li:eq(0) .ContentBox').height(), 
						wrapper.find('>li:eq(1) .ContentBox').height(), 
						wrapper.find('>li:eq(2) .ContentBox').height()
					);
		wrapper.find('.ContentBox')
			.each(function(index)
				{
					var cntBox = jQuery(this);
					var cntBoxHeight = cntBox.height();
					if(cntBoxHeight < maxHeight)
						{
							var heightDiff = maxHeight - cntBoxHeight;
							var minHeightProperty = IE6()?'height':'minHeight';
							
							cntBox.css(minHeightProperty, cntBox.height() + heightDiff + 'px');
						}
				})
		
	}
}

function resizeMainCols()
{
	var c1 = jQuery('#MainContent');
	var c2 = jQuery('#SideContent');
	
	if(c1.size() + c2.size() == 2)
	{		
		var c1h = c1.height();
		var c2h = c2.height();
		
		var maxHeight = Math.max(c1h, c2h);
		
		var minHeightProperty = IE6()?'height':'minHeight';
		
		if(c1h < maxHeight)
		{
			var heightDiff = maxHeight - c1h;
			
			var innerWrapper = c1.find('.ContentBox:first');
			innerWrapper.css(minHeightProperty, innerWrapper.height() + heightDiff + 'px');
		}
		
		if(c2h < maxHeight)
		{
			var heightDiff = maxHeight - c2h;
			var innerWrapper = c2.find('>.SkyScraperBanner>.ContentBox, >.SmallBanner:last>.ContentBox');
			innerWrapper.css(minHeightProperty, innerWrapper.height() + heightDiff + 'px');
		}
	}
}

function initOverlays()
{
    var overlayTriggers = jQuery("a[rel^=#overlay]");
    if(overlayTriggers.size() > 0)
    {
	    overlayTriggers
		    .overlay({ 
			expose: 'white', 
			effect: 'apple',
			top: 'center',
			left: 'center',
			onBeforeLoad: function() { 
			    // grab wrapper element inside content 
			    var wrap = this.getContent().find("div.wrap"); 
			    // load the page specified in the trigger 
			    wrap.load(this.getTrigger().attr("href")); 
			},
			onClose: function() { 
			    // grab wrapper element inside content 
			    var wrap = this.getContent().find("div.wrap"); 
			    // load the page specified in the trigger 
			    wrap.empty(); 
			}
		    });
    }

    var voverlayTriggers = jQuery("a[rel^=#vidOverlay]");
    if(voverlayTriggers.size() > 0)
    {
	    voverlayTriggers
		    .overlay({ 
			expose: 'white', 
			effect: 'apple',
			top: 'center',
			left: 'center',
			target: '#mmmVid'});
    }

    
    var photoOverlayTriggers = jQuery("img[rel^=#photo]");
    if(photoOverlayTriggers.size() > 0)
    {
	    photoOverlayTriggers
		    .overlay({ 
			expose: 'white', 
			effect: 'apple',
			top: 'center',
			left: 'center'
		    });
    }

    var gPhotoOverlayTriggers = jQuery("a[rel^=#gphoto]");
    if(gPhotoOverlayTriggers.size() > 0)
    {
	    gPhotoOverlayTriggers
		    .overlay({
			target: '#gallery',
			expose: 'white', 
			effect: 'apple'

		}).gallery({
			autohide: false,
			speed: 800
		});
	}

   var eOverlay = jQuery('#showInOverlay');
   if(eOverlay.size() > 0)
   {
	// get handle to the API upon initialization by enabling the "api" variable 
	var api = eOverlay.overlay({expose: 'white', top: 'center', api: true}); 
	 
	// open the overlay programatically with this API call 
	api.load(); 
	 
	// retrieve an existing api 
	api = eOverlay.overlay();
   }

}

// social networking overlays
function initSNOverlays()
{
	jQuery('a[rel=snLink]')// social networking overlay triggers
		.click(function()
			{
				var lnk = jQuery(this);
				var target = jQuery(lnk.attr('href'));
					
				if(target.size() > 0)
				{


					uiPT = jQuery(this);
					if (sweepsRegistered()) // visitor registered for sweepstakes, link goes directly to the url
					{





					jQuery('body>.snOverlay').fadeTo('fast', 0.1, function(){jQuery(this).css('display', 'none');}) // close any existing overlays
					target
						.stop()
						.appendTo('body')// reposition selected overlay
						.css({
							position: 'absolute',
							zIndex: 1000,
							left: lnk.offset().left + 'px',
							top: lnk.offset().top + getFullHeight(lnk) + 2  +  'px',
							opacity: 0.1,
							display: 'block'
						})
						.fadeTo('normal', 1, function()// show selected overlay
									{
										var overlay = jQuery(this);
										var closeBtn = overlay.find('a.btnCloseOverlay');
										if(closeBtn.size() == 0) // create close button
										{
											var closeBtn = jQuery('<a class="btnCloseOverlay" href="#" title="close">[X]</a>');
											closeBtn
												.appendTo(overlay)
												.click(function()
													{
														// close overlay
														overlay.fadeTo('fast', 0.1, function(){jQuery(this).css('display', 'none');})
														return false
													});
										}
									});

					}
					else // visitor not registered for sweepstakes, show dialog
					{	
						createFlashRegistrationNoticeDialog();
						jQuery("#RegistrationFlashNotice").dialog('open');
					}
					return false;

				}
			})
}

function fixRoundedButtons()
{
	if(IE() || Opera())
	{
		var RoundedButtons = jQuery('a.LinkButton');
		RoundedButtons
			.each(function()
				{
					var btn = jQuery(this);
					btn.css('visibility', 'hidden')
						.removeClass('LinkButton')
						.addClass('LinkButton2')
						.wrapInner('<span class="span2"></span>')
						.prepend('<span class="span1">&nbsp;</span>')
						.css('visibility', 'visible')
				})
	}
}

function fixRoundedCorners()
{
	if(IE() || Opera())
	{
		var RoundedBoxes = jQuery('.ContentBox');
		RoundedBoxes
			.each(function()
				{
					var box = jQuery(this);
					box.css({
							position: 'relative',
							width: parseInt(box.width()) + 'px',
							height: parseInt(box.height()) + 'px'
						})
						.append(
								'<div class="RoundedBoxTopShadow"></div><div class="RoundedBoxBtmShadow"></div><div class="RoundedBoxRightShadow"></div><div class="RoundedBoxLeftShadow"></div><div class="RoundedBoxTR"></div><div class="RoundedBoxBR"></div><div class="RoundedBoxBL"></div><div class="RoundedBoxTL"></div>'
							);
						
						var boxFixWidth = getInnerWidth(box);
						box.find('>.RoundedBoxBtmShadow, >.RoundedBoxTopShadow').css('width', boxFixWidth + 'px');
						var boxFixHeight = getInnerHeight(box);
						box.find('>.RoundedBoxLeftShadow, >.RoundedBoxRightShadow').css('height', boxFixHeight + 'px');
				})
	}
}

var uiPT = null; // ui popup trigger, stores the link that triggered the UI popup
function initUIPopups()
{
	var rLinks = jQuery('a[rel="#RegistrationNotice"]'); // registration trigger links
	if(rLinks.size() > 0)
	{
		createRegistrationNoticeDialog(); // dynamically create registration dialog
		rLinks.click(function()
				{
					uiPT = jQuery(this);
					if (sweepsRegistered()) // visitor registered for sweepstakes, link goes directly to the url
					{
						if(uiPT.attr('target') == '_blank')
							open(uiPT.attr('href'))
						else
							location.href = uiPT.attr('href');
					}
					else // visitor not registered for sweepstakes, show dialog
					{	
						jQuery(uiPT.attr('rel')).dialog('open');
					}
					return false
				});
	}
}

function robotLookOverlay() {
	if (sweepsRegistered()) {
		location.href = '/build_your_robot.html';
	} else {
					uiPT = jQuery(this);
	createFlashRegistrationNoticeDialog();
	jQuery("#RegistrationFlashNotice").dialog('open');
	}

}

function designLookOverlay() {
	if (sweepsRegistered()) {
		location.href = '/design_your_look.html';
	} else {
					uiPT = jQuery(this);
	createFlashRegistrationNoticeDialog();
	jQuery("#RegistrationFlashNotice").dialog('open');
	}

}
function createFlashRegistrationNoticeDialog()
{
	var d = jQuery('<div id="RegistrationFlashNotice" title="NOTICE" style="display: none"><p>We do not detect that you are an eBay Green Team member. Please register or login to Spread the Word or Send Us Your Creative Reuse Project.</p></div>');
	d.appendTo('body')
		.dialog({
					autoOpen: false,
					width: 400,
					modal: true,
					draggable: false,
					resizable: false,
					buttons: {						
						"Register Now": function()
								{ 
									// user not registered, goes to the registration page
									jQuery(this).dialog("close"); 
									location.href = '/join_us.html';
								}
					}
				});
}


function createRegistrationNoticeDialog()
{
	var d = jQuery('<div id="RegistrationNotice" title="NOTICE" style="display: none"><p>We do not detect that you are an eBay Green Team member. Please register or login to Spread the Word or Send Us Your Creative Reuse Project.</p></div>');
	d.appendTo('body')
		.dialog({
					autoOpen: false,
					width: 400,
					modal: true,
					draggable: false,
					resizable: false,
					buttons: {						
						"Register Now": function()
								{ 
									// user not registered, goes to the registration page
									jQuery(this).dialog("close"); 
									location.href = '/join_us.html';
								}
					}
				});
}

function sweepsRegistered()
{
	//  'sweepsRegistered' cookie == 1 => user registered
	var sweepsRegistered = jQuery.cookie('ebg2SweepsRegistered');
	if(sweepsRegistered)
		if(sweepsRegistered > 1)
			return true
	return false;
}

function initTwitterFeedRotation()
{
	var TwitterFeeds = jQuery('#TwitterFeeds ul');
	if(TwitterFeeds.size() > 0)
		TwitterFeeds.cycle({fx: 'scrollUp', timeout: 6000, pause: 1, sync: true});
}

function initJSTracker()
{
	jQuery('#SNNav a, #SNOverlay ul a')
		.click(function()
			{
				var trackLink = jQuery(this);
				trackThis(trackLink.text());
			})
}

function activateGalleryScroller()
{
	var scrollWrapper = jQuery('.ScrollWrapper');
	if(scrollWrapper.size() > 0)
		jQuery('.scrollable')
			.scrollable({
					size:5,
					clickable: false,
					items: '.scrollable ul',
					loop: false
				});
}

var baTimer = null;
function initBeforeAfterImageRotation()
{
	var targets = jQuery('#SideContent .SkyScraperBanner .GraphicBox img, ul.FeaturedMakeOvers img');
	targets
		.each(function()
			{
				var img = jQuery(this);
				if(!img.attr('before'))
				{
					img.attr('before', img.attr('src'));
					img.attr('after', img.attr('src').replace('.jpg', '_after.jpg'));
				}
			})

	baTimer = setInterval(rotateBeforeAfterImages, 4000);

}

function rotateBeforeAfterImages()
{
	var targets = jQuery('#SideContent .SkyScraperBanner .GraphicBox img, ul.FeaturedMakeOvers img');
	targets
		.each(function()
			{
				var img = jQuery(this);
				if(img.attr('before') == img.attr('src'))
				{
					img.fadeOut(1000, function()
								{
									var img = jQuery(this);
									img.attr('src', img.attr('after'));
									img.fadeIn(1000);
								})
				}
				else
				{
					img.fadeOut(1000, function()
								{
									var img = jQuery(this);
									img.attr('src', img.attr('before'));
									img.fadeIn(1000);
								})
				}
			});
}

function fileUploadedOne(u) {
	jQuery('input[name=BeforePhotoUrl]').val(u);
}

function fileUploadedTwo(u) {
	jQuery('input[name=AfterPhotoUrl]').val(u);
}

function fileUploadedThree(u) {
	jQuery('input[name=ProjectVideoUrl]').val(u);
}

jQuery(function(){
	initMainNav();
	replaceSubmitButtons();
	fixRoundedButtons();
	activateGalleryScroller();
	initOverlays();
	initSNOverlays();
	initUIPopups();
	initTwitterFeedRotation();
	initJSTracker();
	initBeforeAfterImageRotation();
})

jQuery(window).load(function(){
	resizeFeaturedItemsCols();
	resizeMainCols();
	fixRoundedCorners();
})