/* 
   ---------------------------------------------------------------------------- 
   ** /assets/javascript/global.js
   ** author: sam king
   ** description: site-wide javascript file containing all global js functionality
   ** last modified: 2010/01/18
   ---------------------------------------------------------------------------- 
*/
$(function()
{
	if ($.browser.msie)
	{
		$("#home-signup").click(function()
		{
			document.location.href = '/signup/';
		});
		//alert('I\'m Internet Explorer');
		var ddForm = $("section.signup nav li div.login-form").html();
		//alert(ddForm);
		$("#dropdown-login-form").parent().remove();
		$("body").append('<div class="login-form dropdown" id="mastheadLoginForm">'+ddForm+'</div>');
		
	}	
	/*
	   ---------------------------------------------------------------------------- 
	   ** controls the accessibility helpers
	   ---------------------------------------------------------------------------- 
	*/
	helper = 0;
	$("span.helper").addClass('no-help');
	$("span.ac-helper").hide();
	if ($.cookie('show_helper'))
	{
		var helperState = $.cookie('show_helper');
		if (helperState == 'true')
		{
			helper = 1;
			$("span.helper").removeClass('no-help');
			$("span.ac-helper").show();
		}
	}
	$(document).bind('keydown', 'alt+h', function()
	{
		if (helper == 0)
		{
			$("span.helper").removeClass('no-help');
			$("span.ac-helper").show();
			helper = 1;
			$.cookie('show_helper', 'true', { path: '/', domain: '', secure: false });
		}
		else
		{
			$("span.helper").addClass('no-help');
			$("span.ac-helper").hide();
			helper = 0;
			$.cookie('show_helper', 'false', { path: '/', domain: '', secure: false });
		}
	});
	/*
	   ---------------------------------------------------------------------------- 
	   ** sets a default input value based on the title attribute from the field
	   ---------------------------------------------------------------------------- 
	*/
	defaultInputValue = '';
	var $inputs = $('input[type="email"], input[type="text"]');
	$inputs.each(function(i)
	{
		var thisValue = $(this).getValue();
		if (thisValue == "")
		{
			var thisTitle = $(this).attr('title');
			$(this).attr('value', thisTitle);
		}
	});
	/*
	   ---------------------------------------------------------------------------- 
		on focusing an input text field, set the default variable to the initial value and clear the field
	   ---------------------------------------------------------------------------- 
	*/
	$('input[type="email"], input[type="text"]').focus(function()
	{
		currentInputValue = $(this).attr('value');
		defaultInputValue = $(this).attr('title');
		if (currentInputValue == defaultInputValue)
		{
			$(this).attr('value', '');
		}
	});
	/*
	   ---------------------------------------------------------------------------- 
		on blurring the field, check to see if the user has entered legit value
		if not, return the value of the field to the initial default value; if so, do nothing
	   ---------------------------------------------------------------------------- 
	*/
	$('input[type="email"], input[type="text"]').blur(function()
	{
		currentInputValue = $(this).attr('value');
		if (currentInputValue == '')
		{
			$(this).attr('value', defaultInputValue);
		}
		defaultInputValue = '';
	});
	/*
	   ---------------------------------------------------------------------------- 
		this uses the jquery ui select menu script to customize the look and feel of the menu
	   ---------------------------------------------------------------------------- 
	*/
	$('.masthead select').selectmenu({
		style:'dropdown'
	});	
	/*
	   ---------------------------------------------------------------------------- 
		the following controls the mega dropdowns in the main navigation bar
		* 2010/11/01: hoverIntent is in place
		* 2010/11/21: removed wonkiness I hope
	   ---------------------------------------------------------------------------- 
	*/
	focusCounter = 0;
	$(".main-nav .row li a").wrapInner('<span />');
	$(".main-nav .row li a span").vAlign();
	$("a .video").append('<span class="play"></span>');
	function showMega() 
	{
		$(this).addClass('hover')
			.find(".dropdown")
			.fadeTo(100, 0.999);
	};
	function hideMega() 
	{
		$(this).removeClass('hover');
	};
	var config = {    
	     over: showMega,   
	     timeout: 200,
	     sensitivity: 3,
	     out: hideMega   
	};		
	if(!$("html").hasClass('iphone'))
	{
		$(".main-nav > nav > ol > li").hoverIntent(config);
	}
	$(".main-nav .dropdown a").focus(function()
	{
		$(".main-nav nav > ol li").removeClass('hover');
		$(this).closest('.dropdown').parent().addClass('hover');
		$(this).closest('.dropdown').css({'top':'37px', 'opacity':'1'}).show();
	});
	/*
	   ---------------------------------------------------------------------------- 
		this is the login dropdown form in the main header area
	   ---------------------------------------------------------------------------- 
	*/

	loginDropdown = 0;
	if ($.browser.msie)
	{
		loginDiv = '#mastheadLoginForm';
	}
	else
	{
		loginDiv = '.dropdown.login-form';
	}
	
	$(".signup a.login").click(function()
	{
		if (loginDropdown == 1)
		{
			$(loginDiv).livequery(function()
			{
				$(this).fadeTo(100, 0, function()
				{
					$(this).css({
						'top':'-999em'
					});
				});
			});
			$(".signup a.login").removeClass('active');
			$('.overlay').fadeTo(0, 0, function()
			{
				$(this).hide();
			});
			loginDropdown = 0;		
		}
		else
		{
			$("#dropdown-login-form").find('input').removeClass('error');
			$(".overlay").css({'background':'#ffffff'}).fadeTo(0, 0.1).show();
			loginDropdown = 1;
			$(this).css({'z-index':'9999'});
			var lgW = $(this).outerWidth();
			var lgH = $(this).outerHeight() + 4;
			if ($.browser.msie)
			{
				var x = $(this).offset();
				x = Math.round(x.left - 160);
			}
			else
			{
				var x = $(this).position();
				x = Math.round(x.left - 150);
			}
			$(this).addClass('active');
			$(loginDiv).livequery(function()
			{
				$(this).css({'top':lgH+'px', 'left':x+'px', 'z-index':'99999999'})
				.stop()
				.fadeTo(100, 1)
				.show();
			});
		}
		return false;
	});
	$("#dropdown-login-form li.cancel a").click(function()
	{
		$('.overlay').fadeTo(0, 0, function()
		{
			$(this).hide();
		});
		loginDropdown = 0;
		$("#dropdown-login-form").parent().fadeOut(100, function()
		{
			$(this).css({'top':'-999em'});
		}).prev().removeClass('active');
	});
	$(".overlay").click(function()
	{
		if (loginDropdown == 1)
		{
			$(".dropdown.login-form").fadeTo(100, 0, function()
			{
				$(this).css({'top':'-999em'});
			});
			$(".signup a.login").removeClass('active');
			$(this).fadeTo(0, 0, function()
			{
				$(this).hide();
			});
			loginDropdown = 0;
		}
	});
	$("#dropdown-login-form").validate({
		debug: true,
		submitHandler: function(form) {
			form.submit();
		},
		rules: {
			USER: {
				required: true,
				minlength: 4
			},
			password: {
				required: true,
				minlength: true
			}
		}
	});
	/*
	   ---------------------------------------------------------------------------- 
		ALERT BAR - when you close it, a session-length cookie is created which maintains the state throughout the browsing session
	   ---------------------------------------------------------------------------- 
	*/
	if ($.cookie('hide_alert'))
	{
		var alertState = $.cookie('hide_alert');
		if (alertState == 'true')
		{
			
		}
	} 
	else 
	{
		$("section.alert").slideDown(600);
	}
	$(".alert a.close").click(function()
	{
		$(this).parent().parent().parent().slideUp(100);
		$.cookie('hide_alert', 'true', { expires: 7, path: '/', domain: '', secure: false });
		return false;
	});
	/*
	   ---------------------------------------------------------------------------- 
		STAR RATING - any class with a class of 'star' gets turned into a rating thing
		:: REMOVED - 2010.12.20 - SJK - PER John M. ::
	   ---------------------------------------------------------------------------- 
	*/
	/*
		$("div.star-ratings").show();
		$('.starRating').rating(
		{
			callback: function(value, link)
			{
				//alert(value);
			}
		});
	*/
	/*
	   ---------------------------------------------------------------------------- 
		Pagination
		2010.11.22: sjk - added a filter to exclude custom pagination scripts from this (used in weekly specials primarily)
	   ---------------------------------------------------------------------------- 
	*/
	if ($(".pagination ul li.prev").length > 0 && $(".pagination ul li.next").length == 0){
		$(".pagination").not('.custom').find("ul").append('<li class="next disabled"><a href="#" title="Next">Next <span></span></a></li>');
		$(".pagination").not('.custom').find("ul li.prev a").prepend("<span></span>");
		$(".pagination").not('.custom').find("ul li.next").click(function(){
			return false;
		});
	} 
	else if ($(".pagination ul li.next").length > 0 && $(".pagination ul li.prev").length == 0){
		$(".pagination").not('.custom').find("ul").prepend('<li class="prev disabled"><a href="#" title="Prev"><span></span> Prev</a></li>');
		$(".pagination").not('.custom').find("ul li.next a").append("<span></span>");
		$(".pagination").not('.custom').find("ul li.prev").click(function(){
			return false;
		});
	}
	else if ($(".pagination ul li.next").length > 0 && $(".pagination ul li.prev").length > 0){
		$(".pagination").not('.custom').find("ul li.next a").append("<span></span>");
		$(".pagination").not('.custom').find("ul li.prev a").prepend("<span></span>");
	}
	/*
	   ---------------------------------------------------------------------------- 
		Scroll to Top
		2010.11.29: sjk - changed to use the scrollTo plugin as it's more cross-browser friendly than the new scrollTop native function
	   ---------------------------------------------------------------------------- 
	*/
	$("a.top").click(function(){
		$.scrollTo(0, 1500);
		return false;
	});
	/*
	   ---------------------------------------------------------------------------- 
		Overlays (Fancyboxes)
	   ---------------------------------------------------------------------------- 
	*/
	// for Follow Bi-lo email icon link
	$("a[rel='iframe']").fancybox({
		'hideOnContentClick': true,
		'titleShow' : false,
		'autoDimensions' : false,
		'scrolling' : 'auto',
		'height' : 600,
		'width': 725,
		'showNavArrows':false,
	    'type' : 'iframe'
	});
	// for additional images on article detail pages
	$("a[rel='large']").fancybox({
		'hideOnContentClick': true,
		'titleShow' : false,
		'autoDimensions' : true,
		'scrolling' : 'auto',
		'showNavArrows':false
	});
	// for pharmacy links
	$("a[rel='pharmacy']").fancybox({
		'hideOnContentClick': true,
		'titleShow' : false,
		'autoDimensions' : false,
		'scrolling' : 'auto',
		'height' : 540,
		'width': 750,
		'showNavArrows':false,
		'type' : 'iframe'
	});
	/*
	   ---------------------------------------------------------------------------- 
		Cycle functionality for hero images
	   ---------------------------------------------------------------------------- 
	*/
    $(".hero, .db-ctas ul, .fuel-ctas ul").cycle({
    	fx: 'scrollDown',
		timeout: 7000,
		pause:1,
		pager:  '#slideshow-nav div'
	});	
    $(".featured-recipe .recipes, .article-slider .articles").cycle({
		fx: 'scrollDown',
		timeout: 7000,
		pause:1,
		pager:  '#slideshow-nav2 div'
	});	
	/*
	   ---------------------------------------------------------------------------- 
	    Add rel="external" to PDF file links
	   ---------------------------------------------------------------------------- 
	*/
    $("a[href$='pdf']").attr('rel','external');
	/*
	   ---------------------------------------------------------------------------- 
	    ... and actually do something with rel=external links ...
	   ---------------------------------------------------------------------------- 
	*/
    $("a[rel='external']").livequery('click', function()
    {
    	thisHref = $(this).attr('href');
    	window.open(thisHref);
    	return false;
    });
	/*
	   ---------------------------------------------------------------------------- 
	    Return false for blank searches on main search field and email subscription
	   ---------------------------------------------------------------------------- 
	*/
	$("#mainsearch").submit(function()
	{
		var q = $('#keywords').getValue();		
		if (q == "" || q == "Search") {
			return false;
		} else {
			return true;
		}
	});	
	/*
	   ---------------------------------------------------------------------------- 
	    Local Events Calendar Rotator
	   ---------------------------------------------------------------------------- 
	*/		
	$(".calendarCycle").cycle({
    	fx: 'scrollHorz',
		timeout: 0,
		next: '.arrow-right',
		prev: '.arrow-left',
		nowrap: true,
		onPrevNextEvent: 
			function(isNext, zeroBasedSlideIndex, slideElement)
			{
				var currentYear = $('.calendarCycle ul').eq(zeroBasedSlideIndex).find('li.currentYear').html();
				$("#yearNav").setValue(currentYear);
			}
	});	

	/*
	   ---------------------------------------------------------------------------- 
	    weekly ads "more" tooltip popup
	   ---------------------------------------------------------------------------- 
	*/	
	$("a.showTT").click(function()
	{
		var x = $(document).width();
		var y = $(document).height();
		$(".overlay").css({
			'width':x+'px',
			'height':y+'px',
			'position':'fixed'
		});	
		$(".overlay").fadeTo(0, 0.2);
		$(".gm-overlay").removeClass('acc');
		var offset = $(this).parent().parent().parent().offset();
		var left = offset.left;
		var top = offset.top;
		var thumbnail = $(this).parent().parent().parent().find('.thumbnail').html();
		var title = $(this).parent().parent().parent().find('h3').html();
		var description = $(this).parent().parent().parent().find('.desc').html();
		var data_item_title = $(this).parent().parent().parent().find('.atl').attr('data-item-title');
		var data_item_id = $(this).parent().parent().parent().find('.atl').attr('data-item-id');
		$(".gm-overlay h3").html(title);
		$(".gm-overlay .thumbnail").html(thumbnail);
		$(".gm-overlay .ad-content p").html(description);
		$(".gm-overlay .atl").attr('data-item-title',data_item_title);
		$(".gm-overlay .atl").attr('data-item-id',data_item_id);
		var gmOW = $('.gm-overlay').width();
		var gmOH = $('.gm-overlay').height();
		$('.gm-overlay').css({
			'top' : (top - gmOH + 210) + 'px',
			'left' : (left - (140)) + 'px'
		});
		return false;
	});	
	/*
	   ---------------------------------------------------------------------------- 
	    columnizer for category tree
	   ---------------------------------------------------------------------------- 
	*/
	$(".category-tree").columnize({ 
		columns: 3,
		lastNeverTallest: true
	});
	$(".brandList").columnize({ 
		columns: 3,
		lastNeverTallest: true
	});
	/*
	   ---------------------------------------------------------------------------- 
	    clicking and pressing around on the autocomplete
	   ---------------------------------------------------------------------------- 
	*/
	$(".ui-menu-item > a").livequery('click', function()
	{
		var brand = $(this).text();
		$("#searchBrands").setValue(brand);
		$("#search-ad").delay(100).submit();
	});
	$(".ui-autocomplete a.ui-state-hover").livequery('keypress', function(e)
	{
		var brand = $(this).text();
		$("#searchBrands").setValue(brand);
		$("#search-ad").delay(100).submit();
	});	
	/*
	   ---------------------------------------------------------------------------- 
	    brandlist stuff
	   ---------------------------------------------------------------------------- 
	*/
	$("#searchBrands").focus(function()
	{
		$(".brandList").hide();
		$(".letter-nav a").removeClass('active');
	});
	$(".brandList a.close").click(function()
	{
		$(".brandList").hide();
		$(".letter-nav a").removeClass('active');
	});
	/*
	   ---------------------------------------------------------------------------- 
	    weekly ads category dropdown menu
	   ---------------------------------------------------------------------------- 
	*/
	catTree = 0;
	$(".cat-browse a").click(function()
	{
		var coors = $(this).offset();
		var dcW = $("#drop-categories").outerWidth();
		var cbW = $(".cat-browse a img").outerWidth();
		var cbH = $(".cat-browse a img").outerHeight();
		if (catTree == 0)
		{
			var x = $(document).width();
			var y = $(document).height();
			$(".overlay").css({
				'width':x+'px',
				'height':y+'px',
				'position':'fixed'
			});			
			$(".overlay").fadeTo(0, 0.2);
			$("#drop-categories").css(
			{
				'top':(coors.top + 10) + 'px',
				'left':(coors.left - dcW + cbW) +'px'
			});
			catTree = 1;
		}
		else
		{
			catTree = 0;
			$(".overlay").fadeTo(0, 0).hide();
			$("#drop-categories").css(
			{
				'top':'-999em'
			});
		}
	});
	$(".overlay").click(function()
	{
		if (catTree == 1)
		{	
			catTree = 0;
			$(".gm-overlay").removeAttr('style').addClass('acc');
			$(".overlay").fadeTo(0, 0).hide();
			$("#drop-categories").css(
			{
				'top':'-999em'
			});
		}
	});	
	var tallest = 0;
	var $items = $("#storeItems .copy");
	$($items).each(function(i)
	{
		var thisH = $(this).outerHeight();
		if (thisH > tallest)
		{
			tallest = thisH;
		}
	});
	$("#storeItems li .copy").outerHeight(tallest);
	$(".overlay-close a").click(function()
	{
		$(".overlay").fadeTo(0, 0).hide();
		$(".gm-overlay").removeAttr('style').addClass('acc');
	});	
	$(".left-column .view-ad").click(function()
	{
		var href = $(this).find('a').attr('href');
		document.location.href = href;
	});
	/*
	   ---------------------------------------------------------------------------- 
	    weekly ads main getlist function
	   ---------------------------------------------------------------------------- 
	*/
	$("#weeklyAdSearchPagination.pagination a").click(function()
	{
		var page = $(this).attr('data-page');
		if (page && page != '')
		{
			$("#show_page").setValue(page);
			$("#search-results-pagination input[type='submit']").click();
		}
	});
	/*
	   ---------------------------------------------------------------------------- 
	    appends keywords to search string for GA
	   ---------------------------------------------------------------------------- 
	*/
	$("#search-ad").submit(function()
	{
		var keywords = $("#searchBrands").getValue();
		var storeId = $("input[name='storeId']").getValue();
		var action = $(this).attr('action');		
		action = action + 'keywords/' + $.URLEncode(keywords) + '/' + storeId + '/';
		$(this).attr('action', action);
	});
});
/*
   ---------------------------------------------------------------------------- 
    weekly ads main getlist function
   ---------------------------------------------------------------------------- 
*/
var getList = function(store, email, method, itemId, itemTitle, itemQty)
{
	$.ajax({
		type: "POST",
		url: "/index.php/weekly-ads/shoppingList/",
		data: "store="+store+"&email="+email+"&method="+method+"&itemId="+itemId+"&itemTitle="+itemTitle+"&itemQty="+itemQty,
		beforeSend: function()
		{
			$("#shopping-list-functions").livequery(function()
			{
				$(this).empty();
			});
			$("#shopping-list-items").html('<div id="shopping-list-loader"></div>');
		},
		success: function(data)
		{
			$("#shopping-list-loader").fadeOut(100, function()
			{
				$("#shopping-list-items").hide().html(data);
				$("#shopping-list-items").livequery(function()
				{
					var $items = $(this).find('tr');
					slLength = $items.length;
				});
				if (slLength > 0)
				{
					$("#shopping-list-functions").html('<a href="/index.php/weekly-ads/my-list" rel="external" title="Print List" class="printer" target="_blank">Print List</a><a href="javascript:void(0)" title="Email List" class="email">Email List</a>');
				}
				else
				{
					$("#shopping-list-functions").empty();
				}
				$("#shopping-list-items").fadeIn(100);
			});
		}
	});
};
/*
   ---------------------------------------------------------------------------- 
    window onload functionality
   ---------------------------------------------------------------------------- 
*/
window.onload = function()
{
	/*
	   ---------------------------------------------------------------------------- 
	    center images for weekly ad home page
	   ---------------------------------------------------------------------------- 
	*/
	var $waHthumbs = $("article.entry .panel .thumbnail");
	$($waHthumbs).each(function(i)
	{
		var x = $(this).find('img').width();
		var y = $(this).find('img').height();
		$(this).find('img').css({
			'top':((130-y)/2)+'px',
			'left':((130-x)/2)+'px'
		});
	});
	/*
	   ---------------------------------------------------------------------------- 
	    center images for weekly ad sub pages
	   ---------------------------------------------------------------------------- 
	*/
	var $waThumbs = $("#storeItems .thumbnail");
	$($waThumbs).each(function(i)
	{
		var x = $(this).find('img').width();
		var y = $(this).find('img').height();
		$(this).find('img').css({
			'top':((151-y)/2)+'px',
			'left':((134-x)/2)+'px'
		});
	});
};
/*
   ---------------------------------------------------------------------------- 
    this is the end. my only friend, the end.
   ---------------------------------------------------------------------------- 
*/

// copyright 1999 Idocs, Inc. http://www.idocs.com
// Distribute this script freely but keep this notice in place
function numbersonly(myfield, e, dec)
{
var key;
var keychar;

if (window.event)
   key = window.event.keyCode;
else if (e)
   key = e.which;
else
   return true;
keychar = String.fromCharCode(key);

// control keys
if ((key==null) || (key==0) || (key==8) || 
    (key==9) || (key==13) || (key==27) )
   return true;

// numbers
else if ((("0123456789").indexOf(keychar) > -1))
   return true;

// decimal point jump
else if (dec && (keychar == "."))
   {
   myfield.form.elements[dec].focus();
   return false;
   }
else
   return false;
}


// cookie okuma, yazma, silme

// Cerez Gonder
function SetCookie(name,value,hours)
   {
   var expire = "";
   expire = new Date((new Date()).getTime() + hours * 3600000);
   expire = "; expires=" + expire.toGMTString();
   document.cookie = name + "=" + escape(value) + expire;
   return true;
   }
   
// Cerez oku   
function GetCookie(name)
   {
   var cookieValue = "";
   var search = name + "=";
   if(document.cookie.length > 0){
      offset = document.cookie.indexOf(search);
      if (offset != -1){
         offset += search.length;
         end = document.cookie.indexOf(";", offset);
         if (end == -1) end = document.cookie.length;
         cookieValue = unescape(document.cookie.substring(offset, end))
         }
      }
   return cookieValue;
   }
