/*

	Global variables.
	
*/
var BESTBUY = {
	swfVars : {
		version : '9.0.0',
		expressInstallSwfurl : '_functions/js/lib/swf/expressInstall.swf',
		flashvars : false,
		params : {
			wmode : 'opaque'
		}
	}
};
/* For AddThis widget */
var addthis_config = {
      username : 'bestbuyuk',
      services_exclude : 'email,print',
      ui_hover_direction : '-1',
      ui_offset_top : '-9',
      ui_offset_left : '-110',
      ui_header_color : '#003b64',
      ui_header_background: '#f5f5f5'
};




/*

	Init DOM.
	Add interaction/re-styles to the document.
	
*/
function initDom(){


	/*
		Local variables
	*/
	var elTextInputs,					/* Object (jQuery): All inputs of type "text" on the page. */
		elStoreParent,					/* Object (jQuery): Parent element for Store page expandable content. */
		elShoppingParent,				/* Object (jQuery): Parent element for Basket/Cart pages extra content navigation. */
		elZebraStripe,					/* Object (jQuery): All element of class "zebra-stripe" within the wrapper. */
		elOverlayLinks,  				/* Object (jQuery): All element of class "overlay" on the page. */
		elCheckoutContact,				/* Object (jQuery): Page ID - Checkout Contact. */
		elCheckoutDelivery,				/* Object (jQuery): Page ID - Checkout Delivery. */
		scheduleHighlight,				/* Object: Checkout Schedule. */
		overlayLinksOverride,			/* Object (jQuery): Links for Shadowbox. */
		arrHashLinks,					/* Object (jQuery): Anchor links which link to PDP tabs. */
		$pdpTabs,						/* Object (jQuery UI): PDP tab navigation. */
		$specTabs,						/* Object (jQuery UI): PDP spec tab navigation. */
		$conInfoMasterTabs,				/* Object (jQuery UI): PDP connected product info master tab navigation. */
		$conRecommendTabs,				/* Object (jQuery UI): PDP connected product recommended tab navigation. */		
		commControls,					/* Object: activateFormControls() Checkout Contact Prefs. */
		deliveryControls,				/* Object: activateFormControls() Checkout Delivery contact Prefs. */
		elPrintLink,					/* Object (jQuery UI): HTML link element for print page. */
		elPrintListItem;				/* Object (jQuery UI): HTML list element for print page. */


	/*

    	Site-wide Initialisation (required for site frame and most pages).

    */
    

    // Add an extra class to the <body> element for JS-only styling.
    $('body').addClass('js');

    // Replace global search button with a link for visual consistency.
    if($('#site-search').length > 0) {
        globalSearch.init({
            form : '#site-search',
            required : ['#search'],
            element : '<a href="#">Search</a>',
            replace : 'input#search-submit'
        });
    }
    
    // Initialise print page icon for generic pages.
    if($('#nav-pageactions').length > 0) {
    	$('#pa-print').click(function(e){
    		e.preventDefault();
    		window.print();
    	});
    }

    // Initialise behaviour for text inputs.
    elTextInputs = $('input[type=text],input[type=password]');
    if (elTextInputs.length > 0) {
	    fancyTextInputs.init({
	      elements: elTextInputs,
	      overrideClassName: 'keep-default-value',
	      focusClassName: 'text-focus'
	    });
	}
	
	
	/*
    
    	Page/Content Specific Initialisation.
    	
    */
    
    
    // Run specific code depending on page ID (Switch statement is more efficient than If...Then clause).
    currentPageID = $('#wrapper .wrapper-inner').attr('id');

    switch(currentPageID)
    {
    	// Home Page: Initialise tab navigation.
    	case 'home-page':
    		$('div.tabs', $('#home-page')).tabs();
	    	break;

	    // Department Page: Initialise tab navigation.
	    case 'department':
	    	$('div.product-recommended', $('#department')).tabs();
	    	break;

	    // Category Page: Initialise tab navigation.
	    case 'category':
	    	$('div.tabs', $('#category')).tabs();
			$('div.bookend div.product-recommended', $('#category')).tabs();
	    	break;

	    // Store Locator: Initialise tab navigation for image gallery.
	    case 'store-locator':
	    	$('div.tabs', $('#store-locator')).tabs();
	    	break;

	    // Product Details: Initialise tab navigation for image gallery.
	    case 'product-details':
	    	$('div.gallery div.tabs', $('#product-details')).tabs();
	    	$pdpTabs = $('#product-info').tabs();
	    	
	    	// If there's a spec tab, check and create tab navigation within it.
			if($('#product-details-specification').length > 0){
				$specTabs = $('#product-details-specification .tab-content-inner').tabs();
			}
	    	break;
	    	
	   	// Inspiration & Advice: Initialise tab navigation.
	    case 'inspiration-advice-article':
	    	$('div.product-recommended', $('#inspiration-advice-article')).tabs();
	    	break;
	    	
	    // Inspiration & Advice: Initialise tab navigation.
	    case 'inspiration-advice-category':
	    	$pdpTabs = $('#product-info').tabs();
	    	break;
			
		// Connected products: Initialise tab navigation.
	    case 'connected-products':
	    
	    	$('#product-intro-info').tabs();
	    	
	    	// Initialise tabs for Recommended Info and Main Info.
	    	if($('#connected-product-info').length > 0 && $('#connected-recommended').length > 0){

				$conRecommendTabs = $('#connected-recommended').tabs();
				$conInfoMasterTabs = $('#connected-product-info').tabs();
	
				// Switch the other tabs for consistency.
				$('#connected-recommended a').click(function(){
					$conInfoMasterTabs.tabs('select',$(this).parent().prevAll().length);
				});
				$('#connected-product-info > ul li a').click(function(){
					$conRecommendTabs.tabs('select',$(this).parent().prevAll().length);
				});

			}

			// Initialise other tabs.
			$('div.gallery div.tabs', $('#connected-products')).tabs();
			$('.tab-product-info', $('#connected-product-info')).tabs();

			// Initialise carousel and table sorter.
			if($('#connected-product-info').length > 0){
			
				displayCount = ($('#connected-products.subsidised').length>0) ? 3 : 6;

				// Initiliase table sorting for Monthly Plans.
				$('.mobile-plans').tablesorter({
					headers : {
						0 : { sorter : false },
						5 : { sorter : false }
					}
				});
				
				// Initiliase table sorting for Pay As You Go Plans.
				$('#payg-plans').tablesorter({
					headers : { 0 : { sorter : false } }
				});

				// Initialise carousel for gifts/monthly plans.
				giftCarousel = new simpleCarousel();
			  	giftCarousel.init({
			  		'listElement' : $('#nav-carousel'), 
			  		'displayCount' : displayCount
			  	});

			  	// Inialise show/hide relevant 
			  	connectedProductsController.init({
					'carouselEl' : $('#nav-carousel'),
					'tableEl' : $('#options-table')
				});
			}
	    	
	    	break;

	    // Search Page: Initialise tab navigation.
	    case 'search-list':
	    	$('div.tabs', $('#search-list')).tabs();

	    	// Initialise submit onChange for Selects.
	    	$('.search-tools .auto-submit').change(function(){
	    		$(this).parents('form:first').submit();
	    	});
	    	break;

	    // Product List: Initialise view toggle.
	    case 'product-list':
	    	// Initialise submit onChange for Selects.
	    	$('.options-wrapper .auto-submit').change(function(){
	    		$(this).parents('form:first').submit();
	    	});
    	
	    	$('#list-view01, #list-view02').click(function(){
				$.scrollTo('#product-list-view', 300, {axis:'y', offset:-110});
				$('#product-list-view').removeClass('product-recommended-grid').addClass('product-recommended-list');
				$('#list-view01, #list-view02').attr('checked','checked');
			});
			
			$('#browse-view01, #browse-view02').click(function(){
				$.scrollTo('#product-list-view', 300, {axis:'y', offset:-110});
				$('#product-list-view').removeClass('product-recommended-list').addClass('product-recommended-grid');
				$('#browse-view01, #browse-view02').attr('checked','checked');
			});
	    	break;

	    // Checkout: Initialise highlighting for selecting delivery time.
	    case 'checkout-schedule':
	    	scheduleHighlight = highlightSelected();
	    	scheduleHighlight.init({
	    		elements : $('#checkout-schedule table.delivery-grid:first input, #checkout-schedule table.delivery-grid:first label'),
	    		className : 'selected',
	    		levelsUp : 1
	    	});
	    	break;

	    // Checkout: Initialise disabling/enabling for Contact Preferences.
	    case 'checkout-contact':
	    	elCheckoutContact = $('#checkout-contact');
	    	commControls = activateFormControls();
	    	commControls.init({
	    		elements : $('.comm input', elCheckoutContact),
	    		triggers : $('.opt-in input, .opt-in label', elCheckoutContact),
	    		labelClass : 'disabled'
	    	});
	    	break;

	    // Checkout: Initialise disabling/enabling for Checkout Delivery.
	    case 'checkout-delivery':
			elCheckoutDelivery = $('#checkout-delivery');
	    	deliveryControls = activateFormControls();
	    	deliveryControls.init({
	    		elements : $('.save-address input.text', elCheckoutDelivery),
	    		triggers : $('.save-address p.indent input.checkbox, .save-address p.indent label', elCheckoutDelivery),
	    		labelClass : 'disabled'
	    	});
	    	break;

	    // Checkout: Initalise selectbox script for select boxes which require attention from the user.
	    case 'checkout-delivery':
	    case 'confirm-collection':
		case 'payment-details':
	    	selectbox.init({
	    		inactiveClassName : 'inactive-text',
	    		activeClassName : 'active-text'
	    	});
	    	break;

	    // Checkout: Initialise print page icon for checkout.
	    case 'checkout-thank-you':
	    	if($('#title')){
	    		elPrintLink = $('<a href="#">Print your order</a>').click(function(e){
		    		e.preventDefault();
		    		window.print();
		    	});
		    	$('<p id="print"></p>').prependTo('#checkout-thank-you #title').html(elPrintLink);
	    	}
	    	break;
    }


	/*

		Generic Initialisation (modules which could be featured on several pages).

	*/

    
    // Initialise the expandable content area.
	elStoreParent = $('#wrapper .list-stores .expandable-content');
    if(elStoreParent.length > 0) {
        expandableContent.init({
            parentElement : elStoreParent,
            collapsableSections : 'li .store-full-details',
            collapsableHeadings : 'li .store-summary',
            openClassName : 'store-open',
            triggerOpenText : 'View store',
            triggerCloseText : 'Close',
            openElements : [0],
            animate : true,
            animationTime : 500
        });
    }
    
    // Initialise extra content navigation elements for basket/cart pages.
	elShoppingParent = $('#wrapper .continue-shopping');
    if(elShoppingParent.length > 0) {
        contentNavigation.init({
            parentElement: elShoppingParent,
            navigationElement: '.menu',
            eventTrigger: 'mouseover',
            openClassName: 'open',
            animate: false,
            animationType: 'slide'
        });
    }
    
    // Apply zebra stripe to table or list elements.
    elZebraStripe = $('#wrapper .zebra-stripe');
    if(elZebraStripe.length > 0){
    	$('tr:nth-child(even), li:nth-child(even)', elZebraStripe).addClass('alt');
    }

    // Setup Shadowbox where appropriate.
	elOverlayLinks = $('a.overlay:not(.override)');
    if(elOverlayLinks.length > 0) {
	    Shadowbox.setup(elOverlayLinks, {
        	player: 'iframe',
        	height:160,
        	width:320
        });
        /* example: override the resize and use fixed dimensions
        overlayLinksOverride = $('a.overlay.override');
        if (overlayLinksOverride.length > 0) {
	        Shadowbox.setup(overlayLinksOverride, {
	            player: 'iframe',
	            height: 640,
	            width: 640
	        });
        }*/
	} else {
		/*
			Since we're skipping the shadbowbox.init() call and loading shadowbox dependencies ourselves 
			(see $LAB at the bottom of the page), shadowbox-jquery.js ends up appending the shadowbox 
			container div to the body. We should remove this unnecessary element.
		*/
		$('#sb-container').remove();
	}
    
    // Add events to hash links which link to tabs (but don't include tab-nav links).        
    arrHashLinks = $('#wrapper a[href!="#"][href^="#"]:not(#product-info .tab-nav a)');
	arrHashLinks.each(function(){
		if($('#product-info ' + $(this).attr('href')).length > 0){ // Check it's linking to the Tab content.
			$(this).click(function(event){
				event.preventDefault();
				if($pdpTabs){ $pdpTabs.tabs('select',$(this).attr('href')); }
				$.scrollTo('#product-info',	300, {axis:'y', offset:-15});
			});
		}
    });
    
    // Sub-menu sliding effects (used in Inspiration & Advice but could be used anywhere).
    submenu = $('#wrapper li.sub-menu');
    if(submenu.length > 0){

		// Hide sub-menus.
    	$('> ul', submenu).slideUp(0);
    	
    	// Hover state for fake links.
    	$(submenu).hover(function(){
    		$(this).addClass('sub-hover');
    	},function(){
    		$(this).removeClass('sub-hover');
    	});
    	
    	// Accordion effect for sub-menus.
    	$(submenu).click(function(){
    	
    		newItem = $(this);

    		if(!newItem.hasClass('sub-selected')){

	    		curItem = $('.sec-nav li.sub-selected');
	    		curItem.removeClass('sub-selected');
	    		$('ul', curItem).slideUp(500);
	    		
	    		newItem.addClass('sub-selected');
				$('ul', newItem).slideDown(500);
			
			}
    	});
    	
    }


}





/*

	Init Page.
	Run non-DOM reliant code and assign initDom() for Document Ready event.
	
*/
function initPage() {


	/* Local variables */
	var browser = $.browser;	/* Object (jQuery): Browser information. */

	/*
		Image flicker fix for IE6. Browser sniffing is bad - however, this problem is only apparent in IE6
		so it isn't worth telling every other browser to run a Try Catch.
	*/
	if(browser.msie===true && browser.version === '6.0'){
		try{
			document.execCommand('BackgroundImageCache', false, true);
		}catch(e){}
	}

	$(document).ready(function() {
		initDom();
	});


}





// Load dependencies.
if(typeof initSwfObject === 'function') {
	$LAB
	.script('http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js')
		.block(function(){
			initSwfObject(BESTBUY.swfVars.version,BESTBUY.swfVars.expressInstallSwfurl,BESTBUY.swfVars.flashvars,BESTBUY.swfVars.params);
		});
}

$LAB
//.script('_functions/js/third-party/shadowbox/shadowbox.js')
.block()
	//.script('_functions/js/third-party/shadowbox/languages/shadowbox-en.js')
	//.script('_functions/js/third-party/shadowbox/players/shadowbox-iframe.js')
	.script('_functions/js/third-party/jquery-ui/jquery-ui-1.7.1.custom.min.js')
	.script('_functions/js/third-party/jquery/jquery.scrollTo-1.4.2-min.js')
	.script('_functions/js/third-party/tablesorter/jquery.tablesorter.js')
	/* GU - scripts in this block should be combined into a single file for production 
		- and kept in sync with identical block in manager-overlay.js */
	.script('_functions/js/grand-union/activate-form-controls/activate-form-controls.js')
	.script('_functions/js/grand-union/fancy-forms/fancy-text-inputs.js')
	.script('_functions/js/grand-union/highlight-selected/highlight-selected.js')
	.script('_functions/js/grand-union/highlight-selected/highlight-selected-manager.js')
	.script('_functions/js/grand-union/selectbox/selectbox.js')
	.script('_functions/js/grand-union/content-navigation/content-navigation.js')
	.script('_functions/js/grand-union/expandable-content/expandable-content.js')
	.script('_functions/js/grand-union/global-search/global-search.js')
	.script('_functions/js/grand-union/simple-carousel/simple-carousel.js')
	.script('_functions/js/grand-union/connected-products-control/connected-products-control.js')
	/* GU */
	.block()
		//.script('_functions/js/third-party/shadowbox/adapters/shadowbox-jquery.js')
		.block(function(){
			initPage();
		});