////////////////////////////////////////////////////////////////
// Browser
////////////////////////////////////////////////////////////////

scSite.browser = scSite.addComponent('browser',
{
	// Is it IE 6 or less
	isIE6orLess: function()
	{
		return ( $.browser.msie && $.browser.version.substr(0,1) < 7 );
	},
	
	// Is it IE 6 or less
	isIE7orLess: function()
	{
		return ( $.browser.msie && $.browser.version.substr(0,1) < 8 );
	}
	
});



////////////////////////////////////////////////////////////////
// Silent Errors (QoS)
////////////////////////////////////////////////////////////////
//
// Although not implements, this could be used to report back unexpected errors
//

scSite.silentError = function(msg)
{
	
}




////////////////////////////////////////////////////////////////
// Ajax
////////////////////////////////////////////////////////////////
//
// Handles keeping track of ajax requests
//

scSite.ajax = scSite.addComponent('ajax', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			// Setup ajax loader.
			jQuery('body')
				.ajaxStart(comp.started)
				.ajaxStop(comp.stopped);
		},

		inAjax: false,
		callDepth: 0,

		started: function()
		{
			comp.inAjax = true;
			comp.loader.show();
		},

		stopped: function()
		{
			comp.inAjax = false;
			comp.loader.hide();
		},

		// Handles the display of the spinny-wait icon.
		loader:
		{
			selector: '#ajaxLoaderIcon',
			show: function()
			{
				$(comp.loader.selector).show();
			},
			hide: function()
			{
				$(comp.loader.selector).hide();
			}
		}
	});
});




////////////////////////////////////////////////////////////////
// Overlays
////////////////////////////////////////////////////////////////

scSite.overlay = scSite.addComponent('overlay', function(comp)
{
	$.extend(comp,
	{
		depth: 0,
		elements: {},

		// This function should be called every time an overlay (dialog, modal, popup) is shown.
		// It hides select boxes in IE6 because of a bug.
		// It is able to handle multiple overlays but only the last overlay will retain its select boxes.
		// If ther are multiple overlays, the scSite.overlay.close() function will reshow the select boxes of the 2nd to last opened.
		// bgIframe would be preferable but didn't work as expected: http://plugins.jquery.com/project/bgiframe
		open: function(containerId)
		{
			comp.elements[scSite.overlay.depth] = containerId;
			comp.depth++;

			if( scSite.browser.isIE6orLess() )
			{
				var sel = $('select:visible');
				if( containerId != null )
				{
					sel = sel.not('#'+ containerId +' select');
				}
				sel.data('sc-overlay-hidden', true).hide();
			}
		},

		close: function()
		{
			comp.depth--;

			if( scSite.browser.isIE6orLess() )
			{
				// The overlay was closed, so we need to show select boxes we previously hid.
				var sel = null;

				if (comp.depth == 0)
				{
					// There are no more overlays, reshow all select boxes.
					comp.elements = {};
					sel = $('select:hidden');
				}
				else
				{
					// There is still an overlay so only show the selectboxes from the last-most overlay.
					sel = $('#'+ comp.elements[comp.depth - 1] +' select:hidden');
					delete comp.elements[comp.depth]
				}

				sel.each(function()
				{
					if( $(this).data('sc-overlay-hidden') )
					{
						$(this).data('sc-overlay-hidden', false).show()
					}
				});
			}
		}
	});
});




////////////////////////////////////////////////////////////////
// Static Content
////////////////////////////////////////////////////////////////
//
// Allows placeholders to be left in HTML which loads in content when the page is loaded.
// One reason to do this is to leave keywords off of certain pages. It beats using an iFrame because of styling and performance issues
// 
// @idea Because the content is understood to be static, it could be saved in a javascript string and injected without making an ajax call.
//

scSite.staticContent = scSite.addComponent('staticContent',
{
	init: function ()
	{
		$('.sc-static-content').each(function()
		{
			var self = $(this);
			self.load(self.data('sc-static-content-url'));
		});
	}
});


////////////////////////////////////////////////////////////////
// Search
////////////////////////////////////////////////////////////////
scSite.search = scSite.addComponent('search', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			var sws = $('#siteWideSearch');
			
			if( sws.val() == '' )
			{
				return;
			}
			
			var searchDefaultTextList = ['Search Keyword or Item #', 'keyword or item #', 'Search'];
			var searchDefaultTextCurrent = searchDefaultTextList[0];
			
			var colorUnused = $.ifNull(sws.css('color'), '#CCCCCC');
			var colorUsed = '#333333';
			
			var fillSearch = function()
			{
				if( sws.val() == '' )
				{
					sws.val(searchDefaultTextCurrent)
						.css('color', colorUnused);
				}
			}
			
			var clearSearch = function()
			{
				var v = sws.val();
				// Clear and remember text if it is in the default list
				if( $.inArray(v, searchDefaultTextList) >= 0 )
				{
					searchDefaultTextCurrent = v;
					sws.val('');
				}
				sws.css('color', colorUsed);
			}

			sws.bind('focus keypress', clearSearch)
				.blur(fillSearch)
				.closest('form')
					.submit(clearSearch);					
		}
	});
});	





////////////////////////////////////////////////////////////////
// Main Menu
////////////////////////////////////////////////////////////////

scSite.mainMenu = scSite.addComponent('siteMainBlockMenu', function(comp)
{
	$.extend(comp,
	{
		elDeptsTrigger: null,
		elDeptsPopup: null,
		
		elResourcesTrigger: null,
		elResourcesPopup: null,
		
		elServicesTrigger: null,
		elServicesPopup: null,
		
		
		init: function()
		{
			// Init Shop All Departments
			comp.elDeptsTrigger = $('#main_menu_all_depts');
			comp.elDeptsPopup = $('#main_menu_departments');
			
			comp.bindTopMenuMouseEvent
			(
				comp.elDeptsTrigger,
				comp.elDeptsPopup,
				comp.showDepartmentMenu,
				comp.hideDepartmentMenu
			);

			// Sub-menu handling
			comp.elDeptsPopup.delegate('li', 'mouseover', function()
			{
				var self = $(this);
				var off = self.offset();
				off.left += comp.elDeptsPopup.width();

				self.children('div')
					.show()
					.offset(off);
			});

			comp.elDeptsPopup.delegate('li', 'mouseout', function()
			{
				$(this).children('div').hide();
			});


			// Init Resource Center Menu
			comp.elResourcesTrigger = $('#main_menu_resource_center');
			comp.elResourcesPopup = $('#main_menu_resources');
			
			comp.bindTopMenuMouseEvent
			(
				comp.elResourcesTrigger,
				comp.elResourcesPopup,
				comp.showResourcesMenu,
				comp.hideResourcesMenu
			);


			// Init Customer Service Menu
			comp.elServicesTrigger = $('#main_menu_customer_service');
			comp.elServicesPopup = $('#main_menu_service');
			
			comp.bindTopMenuMouseEvent
			(
				comp.elServicesTrigger,
				comp.elServicesPopup,
				comp.showServiceMenu,
				comp.hideServiceMenu
			);	
		},

		bindTopMenuMouseEvent: function(trigger, popup, showFunc, hideFunc)
		{
			trigger.mouseover(showFunc);

			var mouseoutFunc = $.ifRelTargetInside
			(
				trigger,
				popup,
				$.noop,
				hideFunc
			);

			trigger.mouseout(mouseoutFunc);
			popup.mouseout(mouseoutFunc);
		},
			
		hideDepartmentMenu: function()
		{
			comp.elDeptsPopup.hide();
		},

		showDepartmentMenu: function()
		{
			var off = comp.elDeptsTrigger.offset()
			off.top += comp.elDeptsTrigger.height();
			comp.elDeptsPopup.show().offset(off);
		},


		showResourcesMenu: function()
		{
			var off = comp.elResourcesTrigger.offset()
			off.top += comp.elResourcesTrigger.height();
			comp.elResourcesPopup.show().offset(off);
		},

		hideResourcesMenu: function()
		{
			comp.elResourcesPopup.hide();
		},


		showServiceMenu: function()
		{
			var off = comp.elServicesTrigger.offset()
			off.top += comp.elServicesTrigger.height();
			comp.elServicesPopup.show().offset(off);
		},


		hideServiceMenu:  function()
		{
			comp.elServicesPopup.hide();
		}		
		
	});
});


////////////////////////////////////////////////////////////////
// Main Menu (v2)
////////////////////////////////////////////////////////////////

scSite.addComponent('scmenu', function(comp)
{
	$.extend(comp,
	{
		openDelay: 250,
		closeDelay: 100,
		openDelayTimer: null,
		
		init: function()
		{
			$('#menucontainer')
				.delegate('.menu-main-cats',
				{
					mouseover: comp.showSub
				})
				.delegate('.menu-dropdown-bg',
				{
					mouseover: comp.clearHide
				})
				.delegate('.menu-dropdown-bg div',
				{
					mouseover: comp.clearHide
				})
			;
			
			$('#menucontainer').parent('div').mouseover( comp.clearHide );
			//only hide sub menus when we're passing out of the highest-level container div, aka the entire menu section of the page
			$('#menucontainer').parent('div').mouseout( comp.hideSubMenus );
		},
		
		
		timer: -1,
		passedTrigger: false,
		
		showSub: function()
		{
			var elSub = this
			comp.passedTrigger = true
			comp.openDelayTimer = setTimeout(
				function()
				{
					comp.lightUpLink(elSub);
					comp.clearHide();
					comp.hideSubs();
					
					comp.thisSubMenu = "cat"+ elSub.id.replace("menu-link","");
					
					$( '#'+ comp.thisSubMenu )
						.css('left', 0 )
						.css('display', 'block')
					;
				},
				comp.hasLitLink() ? 0 : comp.openDelay
			)
		},
		
		hideSubs: function()
		{
			$( '.menu-dropdown-bg' ).css('display', 'none');
		},
		hideSubsAndDim: function()
		{
			if ( comp.passedTrigger == false )
			{
				comp.hideSubs();
				comp.dimLinks();
			}
		},
		hideSubMenus: function()
		{
			comp.passedTrigger = false;
			clearTimeout( comp.openDelayTimer )
			comp.timer = setTimeout( comp.hideSubsAndDim, comp.closeDelay );
		},
		clearHide: function()
		{
			clearTimeout( comp.timer );
		},
		
		lightUpLink: function(elLink)
		{
			comp.dimLinks();
			$(elLink).addClass('menu-main-cats-hovered')
				.css('background-color', 'white');
		},
		dimLinks: function()
		{
			$('.menu-main-cats').removeClass('menu-main-cats-hovered')
				.css('background-color', '');
		},
		hasLitLink: function()
		{
			return $('.menu-main-cats.menu-main-cats-hovered').size() > 0
		}
	});
});




////////////////////////////////////////////////////////////////
// Product Slider
////////////////////////////////////////////////////////////////
//
// Used in "html/generic/Templates/pageviewFinder.html", "pageviewSearch.html"
//
scSite.productSlider = scSite.addComponent('productSlider', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.sc-pslider').each(function()
			{
				var self = $(this);
				
				var i = 0;
				var groupSize = $.ifNull(self.data('sc-pslider-size'), 4);
				var groupCount = 0;
								
				var lastGroupContainer;
								
				var pageIndex = 0;
				
				var elNav = $('.sc-pslider-nav', self);
				if( ! elNav.size() && $('.sc-pslider-item', self).size() > 3 )
				{
					// There is no navigation already so we will add one.
					elNav = 
						$(
							'<div class="sc-pslider-nav">'+
								'<a href="#" class="sc-pslider-nav-prev">Prev</a>'+
								'<a href="#" class="sc-pslider-nav-next">Next</a>'+
								'<div class="sc-pslider-nav-page">'+
									'Page <span class="sc-pslider-nav-page-current">1</span>'+
									'&nbsp;of&nbsp;<span class="sc-pslider-nav-page-total">1</span>'+
								'</div>'+
							'</div>'
						)
						.prependTo(self);
				}
				
				
				var elBody = $('.sc-pslider-body', self);
				if( ! elBody.size() )
				{
					elBody = $('<div class="sc-pslider-body" />').insertAfter(elNav);
				}
				
				$('.sc-pslider-item', self).each(function()
				{
					// Group items into 4s
					if( ( i++ % groupSize ) == 0 )
					{
						groupCount++;
						lastGroupContainer = $('<div class="sc-pslider-group" />')
							.appendTo(elBody)
							.hide();
					}
					lastGroupContainer.append(this);
				});
				
				
				$('.sc-pslider-nav-page-total', self).html(groupCount);
				
				function slide(pages)
				{
					pageIndex = (groupCount + pageIndex + pages) % groupCount;
					
					$('.sc-pslider-group', self).hide();
					
					//lastGroupContainer = $('.sc-pslider-group:eq('+i+')').show();
					lastGroupContainer = $('.sc-pslider-group:eq('+pageIndex+')', self).show();
					
					$('.sc-pslider-nav-page-current', self).html(pageIndex + 1);
				}

				slide(0);

				// Events
				$('.sc-pslider-nav-prev', self).click(function(ev){ slide(-1); ev.preventDefault(); })
				$('.sc-pslider-nav-next', self).click(function(ev){ slide(1); ev.preventDefault(); })

			});
		}
	})
});


////////////////////////////////////////////////////////////////
// Thin-Banner
////////////////////////////////////////////////////////////////
scSite.thinBanner = scSite.addComponent('thinBanner', function(comp)
{
	$.extend(comp,
	{
		delay: 5000,
		banners: null,
		curBannerIndex: -1,
		
		init: function()
		{
			comp.banners = $('img[name="thinbanners"]');
			if(comp.banners.size())
			{
				comp.startLoop();
			}
		},
		
		startLoop: function()
		{
			comp.curBannerIndex = (comp.curBannerIndex + 1) % comp.banners.size();
			
			comp.banners.hide();
			comp.banners.filter(':eq('+ comp.curBannerIndex +')').css('display', 'inline');
			setTimeout(comp.startLoop, comp.delay)
		}
	});
});


////////////////////////////////////////////////////////////////
// Tabs
////////////////////////////////////////////////////////////////

scSite.tabs = scSite.addComponent('tabUI', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.sc-tabs').tabs();
		}
	});
});


////////////////////////////////////////////////////////////////
// Select Link Box
////////////////////////////////////////////////////////////////
//
// Use this when you need a combo-box which performs a redirect on change.
//


scSite.selectLinkBox = scSite.addComponent('selectLinkBox', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.sc-link-select-box').live('change', function()
			{
				var val = $(this).val();
				if(val != 'clearall' && val != '' && val != null) location.href=val;
			});
		}
	});
});



////////////////////////////////////////////////////////////////
// Accordion
////////////////////////////////////////////////////////////////
/*
scSite.accordion = scSite.addComponent('accordionUI', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.sc-accordion').accordion();			
			
			// Turns lists into ajax accordions
			$('ul.sc-ajax-accordion-list').each(function()
			{
				var self = $(this);
				var elAccordion = $('<div/>').addClass('sc-ajax-accordion');
				
				self.before(elAccordion);
				self.children('li').children('a').each(function()
				{
					var lnk = $(this);
					var url = lnk.data('sc-content-url');
					if( ! url )
					{
						var cid = lnk.data('sc-content')
						if( cid )
						{
							url = '/contentsimple_contentonly_true_content_'+ cid +'.html'
						}
						else
						{
							url = lnk.attr('href');
						}
						
						if( ! url )
						{
							var lnkId = lnk.attr('id');
							if( lnkId.substring(0, 13) == 'anim_content_' )
							{
								cid = lnkId.match(/[0-9]+/);
								url = '/contentsimple_contentonly_true_content_'+ cid +'.html'
							}
						}
					}
					
					var accordionBody = $('<div/>');
					elAccordion
						.append( $('<h3>').append( $('<a href="#"/>').text( $(this).text()) ) )
						.append( accordionBody )
					;					
					accordionBody.data('sc-content-url', url)
				});
			
			}).remove();
			
			// Prepares Ajax Accordions
			$('.sc-ajax-accordion').each(function()
			{
				var firstRun = true;
				
				var self = $(this);
				var container = $('<div />');
				
				self = $(this).before(container).appendTo(container);
				
				self.accordion(
				{
					collapsible: true,
					active: false,
					fillSpace: true,
					
					changestart: function(event, ui)
					{
						if( firstRun )
						{
							firstRun = false;
							container.height(450);
							self.accordion('resize');
						}
						else if( ! ui.newContent.size() )
						{
							container.height('auto');
							firstRun = true;
						}
						
						if( ! ui.newContent.data('sc-content-loaded') && ui.newContent.data('sc-content-url') )
						{
							ui.newContent.html("Loading...");
							
							ui.newContent.data('sc-content-loaded', true);
							$.ajax(
							{
								url: ui.newContent.data('sc-content-url'),
								dataType: 'html',
								context: ui.newContent,
								success: function(data, textStatus, jqXHR)
								{
									$(this).html(data);
								}
							});
						}
					}
				});
			});
		}
	});
});
*/


////////////////////////////////////////////////////////////////
// Lightbox-link
////////////////////////////////////////////////////////////////

scSite.lightboxLink = scSite.addComponent('lightboxLink', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			var lbGroups = $('.lightbox-link-group');
			if( lbGroups.size() < 1 )
			{
				lbGroups = $('body');
			}
			
			$('.lightbox-open').click( function(ev){
				ev.preventDefault()
				comp.openLinkFunc( $(this).data('sc-gallery-index') )
			})
			
			comp.openLinkFunc = openGallery;
			
			lbGroups.each(function()
			{
				var imgList = [];
				var lbGroup = $(this);
				lbGroup.find('.lightbox-link').each(function(i)
				{
					var link = $(this);
					link.data('sc-gallery-index', i)
					var linkImg = link.children('img');

					imgList.push(
						new scSite.item.GalImage(
							link.attr('href'),
							linkImg.attr('src'),
							$.ifNull(link.attr('title'), linkImg.attr('alt'))
						)
					);
				}).click(function(ev)
				{
					ev.preventDefault();
					pg.open($(this).data('sc-gallery-index'));
				});
				
				if( imgList.length )
				{
					pg = scSite.popupImageGallery.newImageGallery(imgList, 0);
				}
			});
			
			function openGallery(index) 
			{
				pg.open(index)
			}
		}
	});
});


////////////////////////////////////////////////////////////////
// Item Comparison
////////////////////////////////////////////////////////////////
//
// Used in "html/generic/Templates/pageviewFinder.html", "pageviewSearch.html"
//

scSite.itemCompare = scSite.addComponent('itemCompare', function (comp)
{
	$.extend(comp,
	{
		setPath: function(p)
		{
			comp.path = p;
		},
		
		path: ''
	});
});



////////////////////////////////////////////////////////////////
// Intelligence
////////////////////////////////////////////////////////////////
//
// Relocated[sc_js_intel] from "html/generic/Templates/static.html"
//

scSite.intel = scSite.addComponent('scIntel', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			// Any useful tracking data can be inserted into _sct with this line of code.
			//   Replace 'test' with the key name and 'data' with the value
			//window['_sct'] = ( typeof( window['_sct'] ) != 'undefined' ? window['_sct'] : '' ) + escape('test')+'='+escape('data')+'&';
			var n = navigator;
			var d = document;
			var s = screen;
			var w = window;
			var ua = n.userAgent;
			var pf = n.platform;
			var ce = n.cookieEnabled;
			var ck = d.cookie;
			var sh = s.height;
			var sw = s.width;
			var sc = s.colorDepth;

			var wtl = ( w.top != w.self ) ? w.top.location : '';		
			var ih = self.innerHeight;
			if( ! ih || ih == 0 )
			{
				ih = d.documentElement.clientHeight;
			}

			var iw = self.innerWidth;
			if( !iw || iw == 0 )
			{
				iw = d.documentElement.clientWidth;
			}

			var rf = d.referrer;
			var wl = window.location;

			prot = (wl.href.substr(0,6) == 'https:') ? 'https:' : 'http:';
			
			// We could do a display:none although that may prevent the image from being loaded, which is the whole point.
			$('<img style="width: 1px; height: 1px; position:absolute; top:0; left: -100;" />')
				.attr('src', prot+'//www.sc-intel.com/tracking/tracking.php?javascript=yes'+'&ua='+escape(ua)+'&pf='+escape(pf)+'&ce='+escape(ce)+'&sh='+escape(sh)+'&sw='+escape(sw)+'&sc='+escape(sc)+'&wtl='+escape(wtl)+'&ih='+escape(ih)+'&iw='+escape(iw)+'&ck='+escape(ck)+'&rf='+escape(rf)+'&wl='+escape(wl)+'&sct='+escape(comp.serializeVariables()) )
				.appendTo('body');
		},
		
		variables: {},
		
		trackVar: function(key, value, addCookie)
		{
			if( addCookie === true )
			{
				createCookie(key, value, 0);
			}
			comp.variables[key] = value;
		},
		
		serializeVariables: function()
		{
			var r = '';
			for( var key in comp.variables )
			{
				r += ( r.length ? '&' : '' ) + escape(key) +'='+ escape(comp.variables[key])
			}
			return r;
		}
	});
});



////////////////////////////////////////////////////////////////
// Back Link
////////////////////////////////////////////////////////////////


scSite.browserBackLink = scSite.addComponent('browserBackLink',
{
	init: function()
	{
		$('a.sc-browser-back-link').live('click', function(){
			history.go(-1);
		});
	}
});




////////////////////////////////////////////////////////////////
// Close Window Link
////////////////////////////////////////////////////////////////


scSite.browserCloseLink = scSite.addComponent('browserCloseLink',
{
	init: function()
	{
		$('a.sc-browser-close-link').live('click', function(){
			window.close();
		});
	}
});




////////////////////////////////////////////////////////////////
// General jQuery Functions (Not Necissarily Related to Shoppers Choice)
////////////////////////////////////////////////////////////////
//
// Most functions belong here which are used like this:
//		$('selector').aFunction()
// 


//
// zebraStrip
////////////////////////////////
/**
 * Gives each row (of a table or other element) a different class than the previous row.
 *
 * e.g., $('table').zebraStripe('tr', ['first', 'second', 'third'])
 * 
 * @param rowSelector string selector for all rows.
 * @param cssClasses array list of classes to be used.
 */
jQuery.fn.zebraStripe = function(rowSelector, cssClasses)
{
	rowSelector = ( typeof rowSelector == 'string' && rowSelector.length > 1 ) ? rowSelector : 'tr';

	if ( ! jQuery.isArray(cssClasses) )
	{
		cssClasses = ['odd', 'even'];
	}

	// If the classes are ['red', 'green', 'blue'], when we are adding the 'red' class to a row,
	// we also need to remove the 'green' and 'blue classes.
	var classInverse = [];
	for( var k in cssClasses )
	{
		var classList = [];
		for( var j in cssClasses )
		{
			if( j == k )
				continue;
			classList.push(cssClasses[j]);
		}
		classInverse[k] = classList.join(' ');
	}

	var classCount = cssClasses.length;
	$(this).find(rowSelector).each(function(i, el)
	{
		i = i % classCount;
		$(el).removeClass(classInverse[i]).addClass(cssClasses[i]);
	});
}



////////////////////////////////////////////////////////////////
// popupModal
////////////////////////////////////////////////////////////////
//
// Relocated[PanelPopup] from "generic/Templates/panel-popup.html"
//

scSite.popupWindow = scSite.addComponent('popupWindow', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.sc-popwin-tggr').live('click', function(ev)
			{
				ev.preventDefault();
				
				var self = $(this);
				
				var classes = self.attr('class').split(' ');
				
				var dim = self.data('sc-popwin-tggr');
				if( ! dim )
				{
					var presets = comp.presets;
					for( var i = 0; i < classes.length; i++ )
					{
						dim = presets[classes[i]];
						if( dim )
						{
							break;
						}
					}
				}
				if( ! dim )
				{
					dim = "500,500";
				}
				
				var dim = dim.split(',');
								
				var target = self.attr('target');
				if( ! target || target.substr(0, 1) == '_' )
				{
					target = '';
				}
				
				var url = $.ifNull(self.attr('href'), self.data('sc-popwin-url'));
				
				comp.openPopup(url, 10, 10, dim[0], dim[1], target);
			});
		},
		
		presets:
		{
			'popwin515': "515,400",
			'popwin550': "550,500",
			'popwin650': "650,500",
			'popwin790': "790,600"
		},
		
		openPopup: function(URL, x, y, width, height, target)
		{
			if( ! target )
			{
				target = "myNewWindow" + width
			}
			
			window.name="MyParentWindow";
			var win = window.open(URL, target, 'toolbar=0,scrollbars=yes,location=0,statusbar=0,menubar=0,resizable=1,width=' + width + ',height=' + height + ',left=' + x + ',top=' + y);
			win.focus();
		}
	});
});



////////////////////////////////////////////////////////////////
// popupModal
////////////////////////////////////////////////////////////////
//
// Relocated[PanelPopup] from "generic/Templates/panel-popup.html"
//

scSite.popupModal = scSite.addComponent('popupModal',
{
	isInit: false,
	init: function ()
	{
		$('.sc-modal-trigger').live('click', function(ev)
		{
			var self = $(this);
			
			if( ! self.modalTrigger('isInit') )
			{
				self.modalTrigger(
				{
					title: self.attr('title'),
					url: self.attr('href'),
					width: self.data('sc-dialog-width'),
					height: self.data('sc-dialog-height'),
					events: {}
				});
			}
			
			self.modalTrigger('fire');

			ev.preventDefault();
		});
	}
	
});

////////////////////////////////////////////////////////////////
// popupHelp
////////////////////////////////////////////////////////////////
//
// Different from popupModal in that this is a click() function
// instead of a live() function, because we want to use
// event.stopPropagation() (which doesn't work with live() )
//

scSite.popupHelp = scSite.addComponent('popupHelp',
{
	isInit: false,
	init: function ()
	{
		$('.sc-atthelp-trigger').click( function(ev)
		{
			ev.stopPropagation();
			
			var self = $(this);
			
			if( ! self.modalTrigger('isInit') )
			{
				self.modalTrigger(
				{
					title: self.attr('title'),
					url: self.attr('href'),
					width: self.data('sc-dialog-width'),
					height: self.data('sc-dialog-height'),
					events: {}
				});
			}
			
			self.modalTrigger('fire');
				
			ev.preventDefault();
		});
	}
	
});


//
// modalTrigger
////////////////////////////////
/**
 * modalTrigger: on click, the element will open up a modal dialog. The title and body may be given immediately or loaded later.
 *
 * e.g.,  $('#opens_a_modal_with_predefined_content').modalTrigger({
 *	title: 'Some title',
 *	body: 'Some body'
 * })
 *
 * e.g.,  $('#opens_a_modal_after_content_is_loaded').modalTrigger({
 *	loadContent: function(data, createAndOpenModal)
 *	{
 *		createAndOpenModal({
 *			title: "This is random "+ Math.random(),
 *			body: getMeAString()
 *		});
 *	}
 * })
 *
 * @param object op
 *  - title
 *  - body
 *  - url
 *  - loadContent
 *  - modalId
 *  - modalParent: selector of the element the modal will be placed into.
 */
$.fn.modalTrigger = function(op)
{
	//alert('are you kidding me?');
	// Special Operations
	if( typeof op === 'string' )
	{
		switch( op )
		{
			case 'isInit':
				return this.data('sc-modal-trigger-init') == true;
			break;
			case 'fire':
				this.data('sc-modal-trigger-fire')();
				return this;
			break;
		}
	}
	
	// Initialize the trigger
	this.each(function()
	{
		var self = $(this);
		
		if( ! self.data('sc-modal-trigger-init') )
		{
			var data = $.extend
			(
				{
					defaultWidth: 520,
					defaultHeight: 300
				},
				op,
				{ events: { click: true } }
			);

			var elDialog = $( data.modalId ? ( '#'+ data.modalId ) : null );

			var loadingContent = false;

			// Function to show the modal dialog.
			self.data('sc-modal-trigger-fire', function (event)
			{
				// We need to load content (if not loaded), created the modal (if not created), and show it.
				if( elDialog.size() )
				{
					// elDialog is defined already so not much to do but open it.
					openFunc();
				}
				else if( data.loadContent )
				{
					// The data needs to be loaded through an external mechanism which will send the data back to createModalAndOpen(data)
					if( ! loadingContent )
					{
						loadingContent = true;
						data.loadContent(data, createModalAndOpen);
					}
				}
				else if( data.url )
				{
					// A url is provided so load it via ajax and display.
					if( ! loadingContent )
					{
						loadingContent = false;
						$.ajax({
							url: data.url,
							data: 'html',
							success: function(c)
							{
								createModalAndOpen({body: c});
							}
						});
					}
				}
				else
				{
					// elDialog is not defined and loadContent isn't defined, so we should have all the data already.
					// The content should be inside data so run createModal now
					createModalAndOpen(data);
				}
			});

			self.data('sc-modal-trigger-init', true);
			
			if( data.events )
			{
				for( k in data.events )
				{
					var evnt = data.events[k];
					if( evnt === true )
					{
						self.bind(k, fire);
					}
					else if( typeof evnt == 'function' )
					{
						self.bind(k, evnt);
					}
				}
			}
		}
		
		
		function fire(ev)
		{
			$(this).modalTrigger('fire');
			ev.preventDefault();
		}
		
		/*
		 * makes elDialog a new element and displays it as a dialog.
		 */
		function createModalAndOpen(newData)
		{
			loadingContent = false;
			
			$.extend(data, newData);
			
			//alert(data.body);

			elDialog = $('<div />')
				.attr( 'id', $.ifNull(data.modalId, $.scuid('scModalTrigger')) )
				.attr( 'title', data.title )
				.append( data.body )
				.hide()
				.appendTo('body');
			
			elDialog.data('sc-modal-reset-scroll', true);
			
			openFunc();
		}

		function openFunc()
		{
			elDialog.dialog({
				modal: true,
				width: $.ifNull(data.width, data.defaultWidth),
				height: $.ifNull(data.height, data.defaultHeight),
				open: function(){ scSite.overlay.open(data.modalId) },
				close: scSite.overlay.close
			});
			
			if( elDialog.data('sc-modal-reset-scroll') )
			{
				// Becuase some windows popped up already scrolled down.
				elDialog.scrollTop(0);
			}
			
		}
	});

	return this;
}


////////////////////////////////////////////////////////////////
// Policy Page (part) popup
////////////////////////////////////////////////////////////////
//
// 
//
scSite.policyPopup = scSite.addComponent('policyPopup', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('.scpolicy-popup').each(function() {
				comp.policyPull($(this), 'popup');
			});
			
			$('.scpolicy-imprint').each(function() {
				comp.policyPull($(this), 'imprint');
			} );
		},
		
		policyPull: function(self, type)
		{
			var classNameList = self.attr('class').split(' ');
			var usableClassName = '';
			var className = '';
			for( var classNameKey in classNameList )
			{
				className = classNameList[ classNameKey ];
				if ( ( className != ( 'scpolicy-' + type ) ) && ( /^scpolicy-/.test( className ) ) )
				{
					usableClassName = className;
					break;
				}
			}
			
			if ( usableClassName != '' )
			{
				var usableId = '#' + usableClassName;
				if(type == 'popup')
				{
					self.click( function() {
						$('#scpolicy-part').remove();
						$('body').append('<div id="scpolicy-part"></div>');
						$('#scpolicy-part').load('/holder_holderaction_policies.html ' + usableId, ( function() {
							if( usableClassName == 'scpolicy-flatrate')
							{
								$(this).prepend('<img src="/images/site-specific/1/logo.gif" style="padding: 15px 0px;"/><div style="text-align:center;"><img src="./images/shipping-policy-banner.jpg" /><br /><br /></div>')
							}
							else 
							{
								$(this).prepend('<img src="/images/site-specific/1/logo.gif"  style="padding: 15px 0px;"/>')
							}
							$(this).dialog({title: self.attr('title'), height:$(usableId).data('sc-dialog-height'), width:$(usableId).data('sc-dialog-width'), modal:true, close:( function(){ $('#scpolicy-part').remove() } )});
						} ) )
					} )
				}
				else if(type == 'imprint')
				{
					self.load('/holder_holderaction_policies.html ' + usableId)
				}
			}
		}
	})
});



////////////////////////////////////////////////////////////////
// Start List (Main Menu)
////////////////////////////////////////////////////////////////
//
// Rewritten[startList]
// startList prepares the main menu with mouse-over and out events.
// Rewritten[startList] from "html\generic\Templates\dropdown_navigation.html"
//

scSite.startList = scSite.addComponent('startList', function(comp)
{
	$.extend(comp,
	{
		init: function()
		{
			$('#tab_list > li').each(function()
			{
				var self = $(this);
				self.mouseover(function()
					{
						self.addClass('over');
						self.children('ul').css( {position: 'absolute', top: self.height()} )
					})
					.mouseout(function()
					{
						self.removeClass('over');
					})
				;
			});
		}
    });
});



////////////////////////////////////////////////////////////////
// Company Menu
////////////////////////////////////////////////////////////////


scSite.companyMenu = scSite.addComponent('companyMenu',
{
	init: function()
	{
		$('#scCompanyMenu_Cart').click(function()
		{
			comp.ga.pageTracker._link(this.href);
			return false;
		});
	}
});

////////////////////////////////////////////////////////////////
// Loading Spinner
////////////////////////////////////////////////////////////////

scSite.loadingSpinner = scSite.addComponent('loadingSpinner',
{
	init: function()
	{
		var spinner = '<div class="sc-loading-spinner" style="display:none;"><img src="/images/loading-spinner-2.gif" height="16" width="16" /></div>';
		$('body').append(spinner);
	},
	/**
	 * showSpinner options object accepts:
	 * 	contextElement: element that spinner will be placed near
	 *	contextTop: positive or negative amount that should shift the top of the spinner in relation to the contextElement
	 *	contextLeft: positive or negative amount that should shift the left edge of the spinner in relation to the contextElement
	 *	forceTop: if you want to force the top of the spinner to a specific coordinate
	 *  forceLeft: if you want to force the left edge of the spinner to a specific coordinate
	**/
	showSpinner: function( options )
	{
		var spinner = $('.sc-loading-spinner');
		if ( options.contextElement )
		{
			spinner.css('top', options.contextTop ? $(options.contextElement).offset().top + ( options.contextTop ) : $(options.contextElement).offset().top);
			spinner.css('left', options.contextLeft ? $(options.contextElement).offset().left - spinner.outerWidth() + options.contextLeft : $(options.contextElement).offset().left - spinner.outerWidth() );
		}
		if ( options.forceTop )
		{
			spinner.css('top', options.forceTop);
		}
		if ( options.forceLeft )
		{
			spinner.css('left', options.forceLeft);
		}
		spinner.css('display','block');
	},
	hideSpinner: function()
	{
		$('.sc-loading-spinner').css('display','none');
	}
});
