$(document).ready(function(){
	
	
	/*var deviceAgent = navigator.userAgent.toLowerCase();
	var agentID = deviceAgent.match(/(iphone|ipod|ipad|IEMobile|Windows CE|NetFront|PlayStation|PLAYSTATION|like Mac OS X|MIDP|UP\.Browser|Symbian|Nintendo|Android)/);

	if (agentID) {
		$('.bg_stretch').remove();
		// do something special
	}*/
	
	
	// Find a store
	var $storeListItems = $('.region, .city');
	
	$storeListItems.click( function(e) {
		
		// Cache $(this)
		// Get the amount of cities in a region list
		// Get the display property of all the city lists
		var $el = $(this),
				cityLength = $el.find('.city').length,
				cityCSS = $el.find('.city').children('ul').css('display');
		
		// If there's only one city in a region, display by default
		if ( cityLength == 1 && cityCSS == 'none' ) {
			$el.find('.city').children('ul').show();
		}
		
		// Set up the arrow switching
		var titleBackground = $el.children('span').css('background-position');
		
		if ( titleBackground === '100% 100%' ) {
			$el.children('span').css({'background-position' : '100% 0%'});
		} else {
			$el.children('span').css({'background-position' : '100% 100%'});
		}
		
		// Slide the sub list
		// $el.children('ul').slideToggle();
		
		$el.children('ul').slideToggle( function() {
			
			// When sliding up, close the children (city) lists
			if ( $(this).css('display') !== 'block' ) {
				$(this).find('.city').children('ul').hide();
			}

		});
		
		// When opening a list, close all the sibling lists
		// and their children.
		var $listSiblings = $el.siblings().children('ul');
		
		$listSiblings.each( function() {
			if ( $(this).css('display') == 'block' ) {
				
				// Also, make sure the arrows are 'closed' and
				// the children (city) lists are closed
				$(this).slideToggle( function() {
					$(this).find('.city').children('ul').hide();
				})
							 .parent()
							 .children('span')
							 .css({'background-position' : '100% 0%'});
			}
		});
		
		// Stop event bubbling
		e.stopPropagation();
	});
	
	function setDesigners(){
		if($("#BrandHeading h2").html() == "All Brands"){
			$("#BrandBreadcrumb li:last").html("All Designers");
			$("#BrandHeading h2").html("All Designers");
			$('.DesignerTemplate').addClass('all-designers');
		}
		$("#BrandHeading, #biography, #products").css('visibility','visible');
	}
	
	function setSearch(){
		// the following clears the search box
		$("#search_query").bind("focus", function(){
			if( this.value == "Search" ) {
				this.value = "";
				$(this).removeClass("default");
			}
		});
		$("#search_query").bind("blur", function(){
			if( !this.value.length ) {
				this.value = "Search";
				$(this).addClass("default");
			}
		});
	}
	
	function setNewsletter(){
		// the following clears the search box
		$("#signup_email").bind("focus", function(){
			if( $("#signup_email").val() == "Sign Up for News" ) {
				$("#signup_email").prev().show();
				$("#signup_email").val("");
				$(this).removeClass("default");
			}
		});
		$("#signup_email").bind("blur", function(){
			if( !$("#signup_email").val().length ) {
				$("#signup_email").prev().hide();
				$("#signup_email").val("Sign Up for News");
				$("#signup_email").addClass("default");
			}
		});
	}
	
	function resizeBackground(){
		var image_width = 1280,
			image_height = 800,
			image_ratio = image_width/image_height,
			browser_actual_width = $(window).width(),
			browser_width = $(window).width() > 940 ? $(window).width() : 940,
			browser_height = $(window).height(),
			browser_ratio = browser_width/browser_height,
			half_height = -parseInt(browser_width/(image_ratio*2), 10),
			half_width = -parseInt((browser_height*image_ratio)/2, 10);

		if(browser_ratio > image_ratio){
			// this is when the width is 100% and centered vertically
			$('.bg_stretch').css({
				'marginTop': half_height,
				'marginLeft':'auto',
				'top':'50%',
				'left':'0', 
				'width':browser_actual_width < 940 ? '940px':'100%',
				'height':'auto',
				'display':'block'
				});
		}else{
			// this is when the height is 100% and centered horizontally
			$('.bg_stretch').css({
				'marginTop': '0',
				'marginLeft':half_width,
				'top':'0',
				'left':'50%',
				'width':'auto',
				'height':'100%',
				'display':'block'
				});
		} 
	}
	
	function readCookie(name) {
		var nameEQ = name + "=";
		var ca = document.cookie.split(';');
		for(var i=0;i < ca.length;i++) {
			var c = ca[i];
			while (c.charAt(0)==' ') c = c.substring(1,c.length);
			if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
		}
		return null;
	}
	
	function eraseCookie(name) {
		createCookie(name,"",-1);
	}
	
	function createCookie(name,value,days) {
		if (days) {
			var date = new Date();
			date.setTime(date.getTime()+(days*24*60*60*1000));
			var expires = "; expires="+date.toGMTString();
		}
		else var expires = "";
		document.cookie = name+"="+value+expires+"; path=/;domain=rollandhill.com;";
	}

	function setBackground(){
		var backgroundCount = 18;
		var backgroundNumber = parseInt(Math.floor(Math.random()*backgroundCount),10) + 1;
		var URL = "http://www.rollandhill.com/template/images/backgrounds/"
		if ($('body').hasClass('homepageBody')){
			setRandomProduct();
			if(readCookie('backgroundNumber') && readCookie('backgroundNumber') == backgroundNumber){
				// have to change the randomProduct down unless it's 0.
				if (backgroundNumber == 1){
					backgroundNumber = backgroundNumber + 1;
				}else{
					backgroundNumber = backgroundNumber - 1;
				}
			}
			eraseCookie('backgroundNumber');
			createCookie('backgroundNumber', backgroundNumber, 0);
			$('.bg_stretch').attr('src', URL + backgroundNumber+'.jpg');
		}else{
			if(readCookie('backgroundNumber')){
				backgroundNumber = readCookie('backgroundNumber');
			}
			eraseCookie('backgroundNumber');
			createCookie('backgroundNumber', backgroundNumber, 0);
			$('.bg_stretch').attr('src', URL + backgroundNumber+'.jpg').css('opacity',.5);
		}
	}
	
	function setRandomProduct(){
		// get random number
		var randomProductLength = $('.ProductURL').length;
		var randomProduct = parseInt(Math.floor(Math.random()*randomProductLength),10) + 1;
		// if there is a cookie and its equal to the random number execute
		//console.log('readCookie("randomProduct") ' + readCookie('randomProduct'));
		//console.log('randomProduct is ' + randomProduct);
		if(readCookie('randomProduct') && readCookie('randomProduct') == randomProduct){
			// have to change the randomProduct down unless it's 0.
			if (randomProduct == 1){
				randomProduct = randomProduct + 1;
			}else{
				randomProduct = randomProduct - 1;
			}
		}
		//console.log('NEW randomProduct is ' + randomProduct);
		eraseCookie('randomProduct');
		createCookie('randomProduct', randomProduct, 0);
		$('#Outer').addClass('Product-' + randomProduct);
		randomProductEq = randomProduct - 1;
		$('.ProductURL:eq('+randomProductEq+')').addClass('ProductURLActive');
	}
	
	
	function twoColumnAlign(items){
		$(items+':odd').addClass('last');
		$(items+':even').addClass('first');
		var index = $(items).length;
		//console.log(index)
		if(index%2 == 1){
			$(items+':last').css('margin-left','163px');
		}
	}
	
	function fourColumnAlign(items){
		$(items+':eq(3)').addClass('last');
		$(items+':eq(7)').addClass('last');
		$(items+':eq(11)').addClass('last');
		$(items+':eq(15)').addClass('last');
		$(items+':eq(4)').addClass('first');
		$(items+':eq(8)').addClass('first');
		$(items+':eq(12)').addClass('first');
		$(items+':eq(16)').addClass('first');
		var index = $(items).length;
		var last_row = parseInt(index/4)*4;
		switch (index % 4){
		
		case 0:
			break;
		case 1:
			$(items+':eq('+last_row+')').css('margin-left','238px');
			break;
		case 2:
			$(items+':eq('+last_row+')').css('margin-left','158px');
			break;
		case 3:
			$(items+':eq('+last_row+')').css('margin-left','78px');
			break;
		}
	}
	
	
	
	function init(){
		setBackground();
		resizeBackground();
		setDesigners();
		setSearch();
		setNewsletter();
		if($('.SubCategoryList').length == 1){
			$('.SubCategoryList').show();
		}
		if($('body').hasClass('bulbsBody')){
			$('#subnav-select option:selected').text('Find a bulb for your light');
			$('#nav-select option:selected').text('Find a bulb for your light');
		}
	
		// need to fix breadcrumb issues with next revision
		$(".Breadcrumb ul:first").show();
		
		if($('#ProductBreadcrumb li:eq(1)').text()=="Bulbs Etc. : "){
			$('.productPage').addClass('bulbsBody');
		}
	
		// need to clean this up
		twoColumnAlign('.CategoryTemplate #LayoutColumn2 .ProductList li');
		twoColumnAlign('.recentBody #LayoutColumn2 .ProductList li');
		twoColumnAlign('.SearchTemplate #LayoutColumn2 .ProductList li');
		fourColumnAlign('.DesignerTemplate #LayoutColumn2 .ProductList li');
		$('.DesignerTemplate #LayoutColumn2 .SubBrandListGrid li:eq(4)').remove();
		fourColumnAlign('.DesignerTemplate #LayoutColumn2 .SubBrandListGrid li');
		fourColumnAlign('.productPage .ProductTinyImageList li');
		fourColumnAlign('.productPage #SideProductRelated li');
		fourColumnAlign('.bulbsBody #LayoutColumn2 .ProductList li');
		//fourColumnAlign('.press-image-style li');
		
		//set listener for window resize
		$(window).resize(resizeBackground);
	}
	
	init();
});

