(function($) {
	oishUtil = {
		defaults: {
			keywordInput: '(cuisines, restaurants, or menu items)',
			locationInput: '(Los Angeles, CA or zipcode)'	
		},
		cache: {
			keyword: '',
			location: '',
			popUpElem: {},
			customDistance: {}
		},
		nowDate : null,
		currTimeStr : null,
		init : function() {
			var dstArray = DstDetect();
			var nowDate = new Date();
			var tzOffset = nowDate.getTimezoneOffset() / 60;
			
			oishUtil.nowDate = nowDate;
			oishUtil.currtimeStr = oishUtil.nowDate.toTimeString();
			oish.config.tzOffset = TimezoneDetect() / 60;
			if (dstArray[0] != '') {
				if (tzOffset == (dstArray[0].getTimezoneOffset() / 60)) {
					oish.config.tzDst = 1;
				} else {
					oish.config.tzDst = 0;
				}
			} else {
				oish.config.tzDst = 0;
			}	
			// Pass oish.config to Oish
			if (oish.config) {
				Oish = oish.config;
			}
			oishUtil.addSearchFormEvents();
			oishUtil.initAutoComplete();
			if ($('div.p_limit select').is('*')) {
				$('div.p_limit select').change(function(evt) {
					var elem = $(evt.currentTarget);
					//var currUri = window.location.toString();
					//var segments = currUri.replace(/http:\/\//, '').split('/');

					//var newUri = '/'+ segments[1] +'/'+ segments[2] + '/'+ segments[3] + '/'+ segments[4] + '/'+ segments[5] +'/'+ elem.val();
					var newUri = Oish.current_uri +'/'+ elem.val();
				
					 window.location.href = newUri;
					//window.location.href = substr_replace(currUri, elem.val(), strrpos(currUri, '/') + 1);
				});
			}
			if (Oish.methodName == 'listings' && $('div.restaurant_listing div.content div.entry_ctnr').is('*')) {
				$('div.restaurant_listing div.content div.entry_ctnr').mouseover(function(evt) {
					$(this).addClass('entrySelected');
				});
				$('div.restaurant_listing div.content div.entry_ctnr').mouseout(function(evt) {
					$(this).removeClass('entrySelected');
				});				
			}
			
			if (Oish.moduleName == 'restaurants' && Oish.methodName == 'index') {
				if ($('#menu-tabs').length > 0) {
					$('#menu-tabs').tabs();
				}
                if ($('#profiler-tabs').length > 0) {
					$('#profiler-tabs').tabs();
				}
			}

			
			if ($('div#account-header div#o-bar a#o-bar-login').is('*')) {
				$('div#account-header div#o-bar a#o-bar-login').click(function(){ 
						oishUtil.modalPopUp('/ajax/instantLogin', {}, function() { 
							$('div#modalPopup').addClass('instantLogin');
							return false });
						$('div#modalPopup form#ajaxLoginForm input[type="submit"]').live('click', oishUtil.instantLogin);
					});
			}
			
			if ($('div.commentListing_ctner div.footer_toolbar').is('*')) {
				$('div.commentListing_ctner div.footer_toolbar span.good').click(oishUtil.voteReview);
				$('div.commentListing_ctner div.footer_toolbar span.bad').click(oishUtil.voteReview);
				$('div.commentListing_ctner div.footer_toolbar a.flag').click(oishUtil.flagReview);
			}
			if ($('div.restaurant_detail div.restaurant_info a.btn_addFav').is('*')) {
				$('div.restaurant_detail div.restaurant_info a.btn_addFav').click(oishUtil.addFavorites);
			}
			if ($('div.restaurant_detail div.restaurant_info a.btn_removeFav').is('*')) {
				$('div.restaurant_detail div.restaurant_info a.btn_removeFav').click(oishUtil.removeFavorites);
			}			
			oishUtil.addShareEvents();
			if ($('body#user_panel div.setting_dropdown').is('*')) {
				$('body#user_panel div#account-header a[title="Settings"]').click(oishUtil.showSettingsMenu);
				
			}
			if ($('div#restaurant-menu-tab form[name="search"] input[name="menuSearch"]').is('*')) {
				$('div#restaurant-menu-tab form[name="search"] input[name="menuSearch"]').focus(function(el) {
					
					if ($(el.currentTarget).val() == 'Food or category (i.e. Lobster, Seafood)') {
						$(el.currentTarget).val('');
					}
					
					
				});
				$('div#restaurant-menu-tab form[name="search"] input[name="menuSearch"]').blur(function(el) {
					if ($(el.currentTarget).val() == '') {
						$(el.currentTarget).val('Food or category (i.e. Lobster, Seafood)');
					}
				});				
					
				
			}
			
			if ($('div#account-header a#ac_logout').is('*'))
			{
				$('div#account-header a#ac_logout').live('click', function(evt) {
					evt.preventDefault();
					if (Oish.fbId > 0) 
					{
					
						FB.logout(function() 
							{
								window.location = '/logout'	;
							});
					} else {
						window.location = '/logout';
					}
					
					
				});
		
			}
        
		},
		showSettingsMenu : function() {
			var settingsMenu = $('body#user_panel div.setting_dropdown');
			settingsMenu.attr({
				top: $('body#user_panel div#account-header a[title="Settings"]').position().top + 10,
				left: $('body#user_panel div#account-header a[title="Settings"]').position().left
			}).slideDown('fast', function () {
					$('body, body#user_panel div#account-header a[title="Settings"]').click(oishUtil.hideSettingsMenu);
				});	
		},
		hideSettingsMenu : function() {
			var settingsMenu = $('body#user_panel div.setting_dropdown');
			$('body, body#user_panel div#account-header a[title="Settings"]').unbind('click', oishUtil.hideSettingsMenu);
			settingsMenu.slideUp('fast');

		},
		addShareEvents : function() {
			if ($('div.restaurant_menuItem div.item_info a.btn_share').is('*')) {
				$('div.restaurant_menuItem div.item_info a.btn_share').bind('click', { shareType: 'menuitem', contentId: Oish.itemId}, oishUtil.sharePopup);
			}

			if ($('div.restaurant_detail div.profiler-tabs-ctner a.btn_share').is('*')) {
				$('div.restaurant_detail div.profiler-tabs-ctner a.btn_share').bind('click', { shareType: 'restaurant', contentId: Oish.restaurantId}, oishUtil.sharePopup);
			}
			
			if ($('div.menu_photos div.c_footer a.btn_share').is('*')) {
				$('div.menu_photos div.c_footer a.btn_share').bind('click', { shareType: 'menuitem_gallery', contentId: Oish.itemId}, oishUtil.sharePopup);
			}

			if ($('div.restaurant_photos div.c_footer a.btn_share').is('*')) {
				$('div.restaurant_photos div.c_footer a.btn_share').bind('click', { shareType: 'restaurant_gallery', contentId: Oish.restaurantId}, oishUtil.sharePopup);
			}
						 
			if ($('div.commentListing_ctner div.entry div.share_toolbar a.btn_share').is('*')) {
				$('div.commentListing_ctner div.entry div.share_toolbar a.btn_share').each(function(idx, elem){
					var reviewId = $('div.commentListing_ctner div.entry:eq('+ idx +')').attr('id').replace('review_', '');
					$(elem).bind('click', { shareType: 'review', contentId: reviewId}, oishUtil.sharePopup);
				});
			}
			if ($('div.restaurant_listing div.rListing div.entryToolbar a.btn_share').is('*')) {
				$('div.restaurant_listing div.rListing div.entryToolbar a.btn_share').each(function(idx, elem) {
					var restId = $('div.restaurant_listing div.rListing div.entry_ctnr:eq('+ idx +')').attr('rel').replace('resultId_', '');
					$(elem).bind('click', { shareType: 'restaurant', contentId: restId}, oishUtil.sharePopup);
				});
			}
			if ($('div.featuredRestaurant div.content div.bizInfo a.btn_share').is('*')) {
				$('div.featuredRestaurant div.content div.bizInfo a.btn_share').each(function(idx, elem){
					var restId = $('div.featuredRestaurant div.content div.entry:eq('+ idx +')').attr('id').replace('featuredId_', '');
					$(elem).bind('click', { shareType: 'restaurant', contentId: restId}, oishUtil.sharePopup);
				});
			}
				
		},
		instantLogin: function() {
			var params = {
				email : $('div#modalPopup form#ajaxLoginForm input[name="email"]').val(),
				pwd : $('div#modalPopup form#ajaxLoginForm input[name="password"]').val(),
				remember: ($('div#modalPopup form#ajaxLoginForm input[name="remember"]').is(':checked')) ? 1 : 0
			}
			$.ajax( { url: '/ajax/instantLoginSubmit', type: 'POST', dataType: 'json', data: params, success: function(jsonObj){
							// Login success
							if (jsonObj.success == true) {
								var accountHeader = (Oish.methodName == 'member') ? jsonObj.user_header_html : jsonObj.header_html;
								$('div#wrapper div#account-header').empty().append(accountHeader);	
							
								Oish.uid = jsonObj.uid;
								Oish.userName = jsonObj.userName;
								Oish.isLogin = true;
								oishUtil.modalClose();
								
							} else {
								$('div#modalPopup a.close').siblings().remove();
								$('div#modalPopup').append(jsonObj.html);
								
							}
							
				
						}
				});
			
			
			
		},
		modalPrompt: function(prompt, callback) {
			var promptMsg = '<div class="modalPrompt"><h5>'+ prompt +'</h5>';
			promptMsg += '<div class="footerNav"><a href="javascript:void(0);" title="Yes" class="btn_red">Yes</a> ';
			promptMsg += '<a href="javascript:void(0);" title="No" class="btn_orange">No</a></div>';
			promptMsg += '</div>';
			
			$('body').append('<div id="modalPopup" class="modalBlock"><div class="clearFloats"></div><div class="container">'+ promptMsg +'</div></div>');
			var popWidth = $('div#modalPopup').width();
			var popID = 'modalPopup';
			//Fade in the Popup and add close button
			$('#modalPopup').fadeIn()
							.css({ 'width': Number( popWidth ) })
							.prepend('<a href="javascript:void(0);" class="close">&nbsp;</a>');
					
			//Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
			var popMargTop = ($('#modalPopup').height() + 80) / 2;
			var popMargLeft = ($('#modalPopup').width() + 80) / 2;
					
			//Apply Margin to Popup
			$('#modalPopup').css({
			        //'margin-top' : -popMargTop,
			        'margin-left' : -popMargLeft
			    });
		    //Fade in Background
		    $('body').append('<div id="fadeModal"></div>'); //Add the fade layer to bottom of the body tag.
		    $('#fadeModal').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies
			$('#modalPopup a.close, #fadeModal').live('click', oishUtil.promptClose);

			$('div.modalPrompt a.btn_red[title="Yes"]').live('click', function(el){
				$(this).die('click');
				oishUtil.promptClose();
				callback();
			});
			$('div.modalPrompt a.btn_orange[title="No"]').live('click', function(el){
				$(this).die('click');
				oishUtil.promptClose();
				
			});
		},
		promptClose: function() {
			$('#modalPopup a.close, #fadeModal').die('click');
			$('#fadeModal, .popup_block').fadeOut(function() {
				$('div.modalPrompt a.btn_red[title="Yes"]').die('click');
				$('div.modalPrompt a.btn_orange[title="No"]').die('click');
				$('#fadeModal, div#modalPopup a.close, div#modalPopup').remove();
			});
					
		},
		modalPopUp: function(ajaxUrl, params, callback) { 
			$.ajax( {url: ajaxUrl, dataType: 'json', type: 'POST', data: params, success: function(jsonObj) {
					
						$('body').append('<div id="modalPopup" class="modalBlock">'+ jsonObj.html +'</div>');
						var popWidth = $('div#modalPopup').width();
						var popID = 'modalPopup';
	
					 	//Fade in the Popup and add close button
					    $('#modalPopup').fadeIn()
										.css({ 'width': Number( popWidth ) })
										.prepend('<a href="javascript:void(0);" class="close">&nbsp;</a>');
					
					    //Define margin for center alignment (vertical   horizontal) - we add 80px to the height/width to accomodate for the padding  and border width defined in the css
					    var popMargTop = ($('#modalPopup').height() + 80) / 2;
					    var popMargLeft = ($('#modalPopup').width() + 80) / 2;
					
					    //Apply Margin to Popup
					    $('#modalPopup').css({
					        //'margin-top' : -popMargTop,
					        'margin-left' : -popMargLeft
					    });
					
					    //Fade in Background
					    $('body').append('<div id="fadeModal"></div>'); //Add the fade layer to bottom of the body tag.
					    $('#fadeModal').css({'filter' : 'alpha(opacity=80)'}).fadeIn(); //Fade in the fade layer - .css({'filter' : 'alpha(opacity=80)'}) is used to fix the IE Bug on fading transparencies 
						$('#modalPopup a.close, #fadeModal').live('click', oishUtil.modalClose);
						callback();
					}
				});
		},
		modalClose: function() {
			$('#fadeModal, .popup_block').fadeOut(function() {
				$('#fadeModal, div#modalPopup a.close, div#modalPopup').remove();
			});
					
		},

		addSearchFormEvents : function() {

			
			if ($('#keywords').val() == '') {
				$('#keywords').val(oishUtil.defaults.keywordInput);
			}
			// search more filter
			if ($('body#user_panel').is('*')) {
				$('div#main_nav a[title="Refine your search"]').click(function() { 
						$('div#search-filters').slideToggle();
						
						_gaq.push(['_trackEvent', 'searchbar', 'click', 'expand']);
					}); 
			} else {				
				$('div#search-more a[title="Refine your search"]').click(function(){
						$('div#search-filters').slideToggle();
						_gaq.push(['_trackEvent', 'searchbar', 'click', 'expand']);
					});
			} 
			$('div#search-filters span.close').click(function() {
						$('div#search-filters').slideToggle();	
						_gaq.push(['_trackEvent', 'searchbar', 'click', 'collapse']);		
					});
			// display html5 geo location share location info
			$('#location').focus(oishUtil.displayHTML5GeoLoc);

			$('#keywords').focus(function(evt){
					var elem = $(evt.currentTarget);
					if (elem.val() == oishUtil.defaults.keywordInput)
					{
						elem.val('');
					} else {
						elem.select();
					}
					oishUtil.cache.keyword = elem.val();
			});
			$('#keywords').focusout(function(evt){
					var elem = $(evt.currentTarget);
					if (elem.val().length == 0) {
						elem.val(oishUtil.defaults.keywordInput);
					}
			});
			$('#location').focus(function(evt){
					var elem = $(evt.currentTarget);
					if (elem.val() == oishUtil.defaults.locationInput)
					{
						elem.val('');
					} else {
						elem.select();
					}
					oishUtil.cache.location = elem.val();
			});
			$('#location').focusout(function(evt){
					var elem = $(evt.currentTarget);
					if (elem.val().length == 0) {
						elem.val(oishUtil.defaults.locationInput);
					}
					if (elem.val() != oishUtil.cache.location) {
						Oish.gotLoc = 'false';
						oishUtil.updateGeoLocationSession();
					}
					
			});
			$('div#search-filters div#options dl dd span.nowOpen').text(getCurrentTime()); 
			$('dl.filterFeatures input[name="bizhour"]').click(function(evt){
				
				if ($(this).is(':checked')) {
					if ($('input[name="customBizHourTime"]').is('*')) {
						$('input[name="customBizHourTime"][type="hidden"]').remove();
						$('input[name="customBizHourDay"][type="hidden"]').remove();
					}
					
				}
			});
								
			oishUtil.customDistanceEvent();
			//oishUtil.updateNeighorCities();
			oishUtil.moreFeaturesEvent();
			oishUtil.moreCuisinesEvent();
			oishUtil.moreRestaurantTypesEvent();
			//oishUtil.moreNeighborCities();
		},
		moreNeighborCities: function() {
			$('#search-filters dl.filterCities dd a[rel="moreCities"]').click(function(evt){
				var elem = $(evt.currentTarget);
				var elemParent = elem.parent();			
				var cElem = {
					element: 'moreCities',
					loc: $('input#location').val(),
					lat : Oish.uLat,
					lng : Oish.uLng,
					distance : $('dl.filterWithin').find('dd input[name="distance"]:checked').val()		
				};
				$.ajax( {url: '/ajax/elements', dataType: 'json', type: 'POST', data: cElem, success: function(jsonObj) {
							if (jsonObj.success == true) {
								var distInput = jsonObj.html;
								oishUtil.displayFilterPopUp(distInput, evt);
								var cityHeading = $('div.additionalFilterCtner div.customMoreCitiesWrapper h4.more_cities_heading');
								cityHeading.each(function(idx) {
									$(this).click(function(evt) {
										
										var cityElement = $(evt.currentTarget);
										cityElement.next().slideToggle();
									});
								
									
								});
								oishUtil.populateMoreCities();
								$('div.additionalFilterCtner div.popFilterFtr a[name="acceptFilter"]').click(oishUtil.acceptMoreCities);
							}
								
						}
					
					
					});

				
			});
		},
		acceptMoreCities: function() {
			$('div.more_cities_child label input[name="more_neighbor\\[\\]"]').each(function(idx) {
				if ($(this).is(':checked')) {				
					if ($('dd input[type="checkbox"][name="neighbor\\[\\]"][value="'+ $(this).val() +'"]').is('*')) {
						$('dd input[type="checkbox"][name="neighbor\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
					} else {
						if (!($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*'))) {
								$('form[name="searchFrm"]').append('<input type="hidden" name="'+ $(this).attr('name') + '" value="'+ $(this).val() +'" />');
						}
					}
				} else {
					if (($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*'))) {
						$('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').remove();
					}
				}
				
			});	
			oishUtil.closeFilterPopUp();	
		},
		populateMoreCities: function() {
			$('dd input[type="checkbox"][name="neighbor\\[\\]"]').each(function(idx){
		
				if ($(this).is(':checked')) {
					$('div.more_cities_child label input[name="more_neighbor\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
				} else {
					$('div.more_cities_child label input[name="more_neighbor\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', false);
				}
			});
			$('form[name="searchFrm"] input[type="hidden"][name="more_neighbor\\[\\]"]').each(function(idx){
				$('div.more_cities_child label input[name="more_neighbor\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
						

			});	
					
		},
		moreRestaurantTypesEvent : function()
		{
			$('#search-filters dl.filterRestTypes dd a[rel="moreRestaurantTypes"]').click(function(evt){
				var elem = $(evt.currentTarget);
				var elemParent = elem.parent();
				$.ajax( {url: '/ajax/elements', dataType: 'json', type: 'POST', data: {element : 'moreRestTypes'}, success: function(jsonObj) {
					
							if (jsonObj.success == true) {
								var distInput = jsonObj.html;
								oishUtil.displayFilterPopUp(distInput, evt);
								oishUtil.populateRestaurantTypesFilter();
								$('div.additionalFilterCtner div.popFilterFtr a[name="acceptFilter"]').click(oishUtil.acceptRestaurantTypesFilter);

							}
						}
					});	
					_gaq.push(['_trackEvent', 'searchbar', 'click', 'moreRestaurantTypes']);
				});
		},
		populateRestaurantTypesFilter: function() {

			$('dd input[type="checkbox"][name="resttypes\\[\\]"]').each(function(idx){
				if ($(this).is(':checked')) {
					$('div.more_resttypes_child label input[name="more_resttypes\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
				} else {
					$('div.more_resttypes_child label input[name="more_resttypes\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', false);
				}
			});
			$('form[name="searchFrm"] input[type="hidden"][name="more_resttypes\\[\\]"]').each(function(idx){
				$('div.more_resttypes_child label input[name="more_resttypes\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
			});	
		},
		acceptRestaurantTypesFilter: function() {
			$('div.more_resttypes_child label input[type="checkbox"]').each(function(idx){
				switch ($(this).attr('id')) {
					case 'more_resttypes_delis-delicatessens':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_resttypes_fast-foods':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_resttypes_bars-grills':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_resttypes_family-style-restaurants':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_resttypes_steakhouses':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_resttypes_vegetarian':
						if ($(this).is(':checked')) {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterRestTypes input[name="resttypes\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					default:
						
						if ($(this).is(':checked')) {
							if (!($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*'))) {
								$('form[name="searchFrm"]').append('<input type="hidden" name="'+ $(this).attr('name') + '" value="'+ $(this).val() +'" />');
							}
						} else {
							$('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').remove();
						}
						break;
				}
			});
			oishUtil.closeFilterPopUp();
		},
		moreCuisinesEvent : function()
		{
			$('#search-filters dl.filterCuisines dd a[rel="moreCuisines"]').click(function(evt){
				var elem = $(evt.currentTarget);
				var elemParent = elem.parent();
				$.ajax( {url: '/ajax/elements', dataType: 'json', type: 'POST', data: {element : 'moreCuisines'}, success: function(jsonObj) {
					
							if (jsonObj.success == true) {
								var distInput = jsonObj.html;
								oishUtil.displayFilterPopUp(distInput, evt);
								oishUtil.populateCuisinesFilter();
								$('div.additionalFilterCtner div.popFilterFtr a[name="acceptFilter"]').click(oishUtil.acceptCuisinesFilter);

							}
						}
					});	
					_gaq.push(['_trackEvent', 'searchbar', 'click', 'moreCuisines']);
				});
		},
		populateCuisinesFilter: function() {

			$('dd input[type="checkbox"][name="cuisines\\[\\]"]').each(function(idx){
				if ($(this).is(':checked')) {
					$('div.more_cuisines_child label input[name="more_cuisines\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
				} else {
					$('div.more_cuisines_child label input[name="more_cuisines\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', false);
				}
			});
			$('form[name="searchFrm"] input[type="hidden"][name="more_cuisines\\[\\]"]').each(function(idx){
				$('div.more_cuisines_child label input[name="more_cuisines\\[\\]"][value="'+ $(this).val() + '"]').attr('checked', true);
			});	
		},
		acceptCuisinesFilter: function() {
			$('div.more_cuisines_child label input[type="checkbox"]').each(function(idx){
				switch ($(this).attr('id')) {
					case 'more_cuisines_american':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_cuisines_chinese':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_cuisines_mexican':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_cuisines_japanese':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_cuisines_italian':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					case 'more_cuisines_mediterranean':
						if ($(this).is(':checked')) {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', true);
						} else {
							$('dl.filterCuisines input[name="cuisines\\[\\]"][value="'+ $(this).val() +'"]').attr('checked', false);
						}
						break;
					default:
						
						if ($(this).is(':checked')) {
							if (!($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*'))) {
								$('form[name="searchFrm"]').append('<input type="hidden" name="'+ $(this).attr('name') + '" value="'+ $(this).val() +'" />');
							}
						} else {
							$('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').remove();
						}
						break;
				}
			});
			oishUtil.closeFilterPopUp();
		},
		moreFeaturesEvent: function() {
			$('#search-filters dl.filterFeatures dd a[rel="moreFeatures"]').click(function(evt){
				var elem = $(evt.currentTarget);
				var elemParent = elem.parent();
				$.ajax( {url: '/ajax/elements', dataType: 'json', type: 'POST', data: {element : 'moreFeatures'}, success: function(jsonObj) {
					
							if (jsonObj.success == true) {
								var distInput = jsonObj.html;
								oishUtil.displayFilterPopUp(distInput, evt);
								var featureHeading = $('div.additionalFilterCtner div.customAdditionalFeaturesWrapper h4.additional_features_heading');
								featureHeading.each(function(idx) {
									$(this).click(function(evt) {
										var featElem = $(evt.currentTarget);
										featElem.next().slideToggle();
									});
								
								});

								$('label[for="custom_bizhour_filter_open_now"]').next().text(getCurrentTime());
								$('input#custom_bizhour_filter_open_now').click(function(evt){
									if($(this).is(':checked')) {
										$('dl.filterFeatures input[name="bizhour"]').attr('checked', true);
										if ($('input#custom_bizhour_filter_custom_hour').is(':checked')) {
											$('input#custom_bizhour_filter_custom_hour').attr('checked', false);
										}
									} else {
										$('dl.filterFeatures input[name="bizhour"]').attr('checked', false);
									}
								});
								$('#custom_hour_from_time').val(getCurrentTime().toLowerCase());
								$('select#custom_hour_from_day').find('option[value="'+ oishUtil.nowDate.getDay() +'"]').attr('selected', true);
								$('#custom_hour_from_time').keydown(oishUtil.ignoreTimeChars);
								$('#custom_hour_from_time').focus(function() { $(this).select(); });
								$('#custom_hour_from_time').focusout(oishUtil.validateTimeInput);
								$('input#custom_bizhour_filter_custom_hour').click(function(evt) {
									if ($(this).is(':checked')) {
										var tmpObj = {};
										tmpObj.currentTarget = $('#custom_hour_from_time');
										if (!(oishUtil.validateTimeInput(tmpObj))) {
											$(this).attr('checked', false);
										} else {
											if ($('input#custom_bizhour_filter_open_now').is(':checked')) {
												$('input#custom_bizhour_filter_open_now').attr('checked', false);
													$('dl.filterFeatures input[name="bizhour"]').attr('checked', false);
											}
										}
									}
								});
								$('input#features_filter_payment_method_all').click(function(evt) { 
									$('div.additional_features_child input[name="features_filter_payment_method\\[\\]"]').each(function(idx) {
										if ($(this).val() != 'All') {
											$(this).attr('checked', false);
										}
									});
								});
								$('div.additional_features_child input[name="features_filter_payment_method\\[\\]"]').each(function(idx){
									if ($(this).val() != 'All') {
										$(this).click(function(evt) {
											if ($('input#features_filter_payment_method_all').is(':checked')) {
												$('input#features_filter_payment_method_all').attr('checked', false);
											}
										});
									}
								});
								$('input#features_filter_meals_served_all').click(function(evt) { 
									$('div.additional_features_child input[name="features_filter_meals_served\\[\\]"]').each(function(idx) {
										if ($(this).val() != 'All') {
											$(this).attr('checked', false);
										}
									});
								});
								$('div.additional_features_child input[name="features_filter_meals_served\\[\\]"]').each(function(idx){
									if ($(this).val() != 'All') {
										$(this).click(function(evt) {
											if ($('input#features_filter_meals_served_all').is(':checked')) {
												$('input#features_filter_meals_served_all').attr('checked', false);
											}
										});
									}
								});
								$('input#features_filter_parking_all').click(function(evt) { 
									$('div.additional_features_child input[name="features_filter_parking\\[\\]"]').each(function(idx) {
										if ($(this).val() != 'All') {
											$(this).attr('checked', false);
										}
									});
								});
								$('div.additional_features_child input[name="features_filter_parking\\[\\]"]').each(function(idx){
									if ($(this).val() != 'All') {
										$(this).click(function(evt) {
											if ($('input#features_filter_parking_all').is(':checked')) {
												$('input#features_filter_parking_all').attr('checked', false);
											}
										});
									}
								});
								$('input#features_filter_alcohol_all').click(function(evt) { 
									$('div.additional_features_child input[name="features_filter_alcohol\\[\\]"]').each(function(idx) {
										if ($(this).val() != 'All') {
											$(this).attr('checked', false);
										}
									});
								});
								$('div.additional_features_child input[name="features_filter_alcohol\\[\\]"]').each(function(idx){
									if ($(this).val() != 'All') {
										$(this).click(function(evt) {
											if ($('input#features_filter_alcohol_all').is(':checked')) {
												$('input#features_filter_alcohol_all').attr('checked', false);
											}
										});
									}
								});
								$('div.additionalFilterCtner div.popFilterFtr a[name="acceptFilter"]').click(oishUtil.acceptFeaturesFilter);
								oishUtil.populateFeaturesFilter();
									
							}
						}
					});
					_gaq.push(['_trackEvent', 'searchbar', 'click', 'moreFeatures']);
			});	
		},
		populateFeaturesFilter: function() {
			if ($('input[name="customBizHourTime"]').is('*')) {
				$('input#custom_hour_from_time').val(convertTime($('input[name="customBizHourTime"]').val()).toLowerCase());
				$('select#custom_hour_from_day').find('option[value="'+ $('input[name="customBizHourDay"]').val() +'"]').attr('selected', true);
				$('input#custom_bizhour_filter_custom_hour').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="bizhour"]').is(':checked')) {
				$('input#custom_bizhour_filter_open_now').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="features\\[\\]"][value="general-drive-thru"]').is(':checked')) {
				$('input#features_filter_general-drive-thru').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="features\\[\\]"][value="payment-method-credit-cards"]').is(':checked')) {
				$('input#features_filter_payment-method-visa').attr('checked', true);
				$('input#features_filter_payment-method-master-card').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="features\\[\\]"][value="general-delivery"]').is(':checked')) {
				$('input#features_filter_general-delivery').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="features\\[\\]"][value="general-take-out"]').is(':checked')) {
				$('input#features_filter_general-take-out').attr('checked', true);
			}
			if ($('dl.filterFeatures input[name="features\\[\\]"][value="internet-free"]').is(':checked')) {
				$('input#features_filter_internet-free').attr('checked', true);
			}
			$('div.additional_features_child ul li input[type="checkbox"]').each(function(idx){
					switch($(this).attr('id')) {
						case 'custom_bizhour_filter_custom_hour':
							break;
						case 'custom_bizhour_filter_open_now':
							break;

						default:
					 		if ($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*')) {
					 			$(this).attr('checked', true);
				 			}
				 			break;
					}
				});
			
		},
		acceptFeaturesFilter: function() {
			
			$('div.additional_features_child ul li input[type="checkbox"]').each(function(idx){
				switch ($(this).attr('id')) {
					case 'custom_bizhour_filter_open_now':
						break;
					case 'custom_bizhour_filter_custom_hour':
						if ($(this).is(':checked')) {
							if ($('input[name="customBizHourTime"]').is('*')) {
								$('input[name="customBizHourTime"]').val(convertTime($('#custom_hour_from_time').val()));
								$('input[name="customBizHourDay"]').val($('#custom_hour_from_day').val());
							} else {
								var bizHourInput = '<input type="hidden" name="customBizHourTime" value="'+ convertTime($('#custom_hour_from_time').val()) +'" />';
								bizHourInput += '<input type="hidden" name="customBizHourDay" value="'+ $('#custom_hour_from_day').val() +'" />';
								$('form[name="searchFrm"]').append(bizHourInput);
							}
						} else {
							if ($('input[name="customBizHourTime"]').is('*')) {
								$('input[name="customBizHourTime"]').remove();
								$('input[name="customBizHourDay"]').remove();
							}
						}
						break;
					case 'features_filter_general-drive-thru':
						if ($(this).is(':checked')) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-drive-thru"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-drive-thru"]').attr('checked', false);
						}
						break;
					case 'features_filter_payment-method-visa':
						if ($(this).is(':checked') && ($('input#features_filter_payment-method-master-card').is(':checked'))) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="payment-method-credit-cards"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="payment-method-credit-cards"]').attr('checked', false);
						}
						break;
					case 'features_filter_payment-method-master-card':
						if ($(this).is(':checked') && ($('input#features_filter_payment-method-visa').is(':checked'))) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="payment-method-credit-cards"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="payment-method-credit-cards"]').attr('checked', false);
						}
						break;
					case 'features_filter_general-delivery':
						if ($(this).is(':checked')) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-delivery"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-delivery"]').attr('checked', false);
						}
						break;
					case 'features_filter_general-take-out':
						if ($(this).is(':checked')) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-take-out"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="general-take-out"]').attr('checked', false);
						}
						break;
					case 'features_filter_internet-free':
						if ($(this).is(':checked')) {
							$('dl.filterFeatures input[name="features\\[\\]"][value="internet-free"]').attr('checked', true);
						} else {
							$('dl.filterFeatures input[name="features\\[\\]"][value="internet-free"]').attr('checked', false);
						}
						break;
					default:
						
						if ($(this).is(':checked')) {
							if (!($('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').is('*'))) {
								$('form[name="searchFrm"]').append('<input type="hidden" name="'+ $(this).attr('name') + '" value="'+ $(this).val() +'" />');
							}
						} else {
							$('form[name="searchFrm"] input[type="hidden"][name="'+ $(this).attr('name') +'"][value="'+ $(this).val() +'"]').remove();
						}
						break;
				}
			});
			oishUtil.closeFilterPopUp();
		},
		customDistanceEvent: function() {
			$('#search-filters dl.filterWithin dd a[rel="customDistance"]').click(function(evt){
					var elem = $(evt.currentTarget);
					var elemParent = elem.parent();
					oishUtil.cache.customDistance = elem;
					$.ajax( {url: '/ajax/elements', dataType: 'json', type: 'POST', data: {element : 'customDistance'}, success: function(jsonObj) {
					
						if (jsonObj.success == true) {
						
							var distInput = jsonObj.html;
							oishUtil.displayFilterPopUp(distInput, evt);
							$('div.additionalFilterCtner div.popFilterFtr a[name="acceptFilter"]').click(function(ev) {
								var tarElem = $(evt.currentTarget);
								var tarParent = tarElem.parent();
								var customDistance = trim($('#customDistance').val());
								customDistance = customDistance.replace(/\D/, '');
								var distRadio = '<input type="radio" name="distance" value="'+ customDistance +'" id="customDistRadio" /><label for="customDistRadio"> ';
								distRadio += customDistance +' miles</label>';
								if (customDistance == '') {
									return false;
								}
								$(tarParent).empty().append(distRadio);
								$($(tarParent).parent()).find('dd input[name="distance"]:checked').attr('checked', '');
								$('#customDistRadio').attr('checked', 'checked');
								oishUtil.closeFilterPopUp();
							});
						}
					}});
					_gaq.push(['_trackEvent', 'searchbar', 'click', 'customDistance']);
			});			
		},
		displayFilterPopUp: function(elem,evt) {
			if ($('div.additionalFilterCtner').is('*')) {
				oishUtil.closeFilterPopUp();
			}
			$('body').append(elem);
			var elemPos = $(evt.currentTarget).position();
			var elemWidth = $('div.additionalFilterCtner').width();
			var elemLeft = ((elemPos.left + elemWidth) > $(window).width()) ? ($(window).width() - elemWidth - 50) : elemPos.left;

			oishUtil.cache.popUpElem = $(evt.currentTarget);
			$('div.additionalFilterCtner').css({ position: 'absolute',
												zIndex:	10000,
												top : (elemPos.top + 15)+ 'px',
												left : elemLeft + 'px'}).fadeIn();
			$(window).bind('resize', oishUtil.positionFilterPopup);			
			$('div.additionalFilterCtner div.popFilterFtr a[name="cancelFilter"]').bind('click', oishUtil.closeFilterPopUp);
		},
		positionFilterPopup: function(evt) {
			var pos = $(oishUtil.cache.popUpElem).position();
			var elemWidth = $('div.additionalFilterCtner').width();
			var elemLeft = ((pos.left + elemWidth) > $(window).width()) ? ($(window).width() - elemWidth - 30) : pos.left;

			$('div.additionalFilterCtner').css({ top: (pos.top + 15) + 'px', left: elemLeft + 'px' });			
		},
		closeFilterPopUp: function() {
			$(window).unbind('resize', oishUtil.positionFilterPopup);
			$('div.additionalFilterCtner').remove();
			oishUtil.cache.popUpElem = {};	
		},
		displayHTML5GeoLoc : function(evt) {
			var locPrompt = $.cookie('locPrompt');
			Oish.locPrompt = locPrompt;
			if (Oish.locPrompt == 'true') {
				return false;
			} else {
				if (navigator.geolocation) {
					//$('#geo_note').show();
					navigator.geolocation.getCurrentPosition(oishUtil.getLocSuccess, oishUtil.getLocError,{ maximumAge:Infinity, timeout:0 });
				}
				Oish.locPrompt = true;
			//	$.cookie('oish_sloc_dis', 1);
			}
		},
		updateGeoLocationSession : function() {
			$.ajax( {url: '/zipcodes/ajax/updateGeoLocationSession', dataType: 'json', type: 'POST', data: Oish, success: function(jsonObj) {

							}
					});
		},
		updateNeighorCities : function() {
			var neighborInput = $('div#options dl.filterCities');
			var neighbor = { 
				loc : $('#location').val(),
				lat : Oish.uLat,
				lng : Oish.uLng,
				distance : $('dl.filterWithin').find('dd input[name="distance"]:checked').val()
			};
			if ($('#location').val() == oishUtil.defaults.locationInput) {
				return false;
			}
			$.ajax( {url: '/zipcodes/ajax/getNeighborCities', dataType: 'json', type: 'POST', data: neighbor, success: function(jsonObj) {
								if (jsonObj.success == true) {
									var neighborcount = 0;
									var neighbordd = '';
									if ($('dd input[type="checkbox"][name="neighbor\\[\\]"]').is('*')) {
										$('dd input[type="checkbox"][name="neighbor\\[\\]"]').parent().remove();
									}
									for(var city in jsonObj.cities) {
										for(var neigh in jsonObj.cities[city]) {
											var neighborchecked = ($.inArray(jsonObj.cities[city][neigh].cityvalue, Oish.neighbors) != -1) ? 'checked="checked"' : '';
											neighborcount += 1;
											neighbordd = '<dd><input type="checkbox" value="'+ jsonObj.cities[city][neigh].cityvalue +'" name="neighbor[]" ';
											neighbordd += neighborchecked +' id="neighbor_'+ neighborcount +'" />';
											neighbordd += '<label for="neighbor_'+ neighborcount +'"> '+ jsonObj.cities[city][neigh].cityname +' </label></dd>';
											$(neighbordd).insertAfter($(neighborInput).find('dt'));
										}						
									}
								}
							}
				});	
		},
		getLocSuccess : function(position) {
			var posLat = position.coords.latitude;
			var posLng = position.coords.longitude;
			var param = { lat : posLat, lng: posLng};
			$.ajax( {url: '/zipcodes/ajax/getZipcodeFromGeoLocation', dataType: 'json', type: 'POST', data: param, success: function(jsonObj) {
								
									if (jsonObj.success == true) {
										Oish.uLng = posLng;
										Oish.uLat = posLat;
										Oish.uLocality = (jsonObj.zipcode.city_alias.indexOf('(') == -1) ? 
																		ucwords(jsonObj.zipcode.city_alias.toLowerCase()) : jsonObj.zipcode.city_alias;
										
										Oish.uRegion = jsonObj.zipcode.state;
										Oish.uCountry = 'US';
										Oish.uTimezone = jsonObj.zipcode.timezone;
										Oish.uZipcode = jsonObj.zipcode.zipcode;
										Oish.uCity = jsonObj.zipcode.city;
										Oish.locPrompt = 'true';
										Oish.gotLoc = 'true';
										(jsonObj.zipcode.city_alias.indexOf('(') == -1) ? $('#location').val(Oish.uLocality +', '+ Oish.uRegion) 
															: $('#location').val(Oish.uLocality);
										oishUtil.cache.location = $('#location').val();
										oishUtil.updateGeoLocationSession();
										$('#geo_note').hide();
										$.cookie('locPrompt', 'true');
									} else {
									//	oishUtil.getLocError({ code: error.POSITION_UNAVAILABLE});
									}
							}
					});
		},
		getLocError : function(error) {
			switch(error.code) {
				case error.PERMISSION_DENIED:
					$('#geo_note div').empty().append('<p class="error">Unable to get current location. Location not provided.');
					break;
				case error.POSITION_UNAVAILABLE:
					$('#geo_note div').empty().append('<p class="error">Current location not available.');
					break;
				case error.TIMEOUT:
					navigator.geolocation.getCurrentPosition(oishUtil.getLocSuccess, oishUtil.getLocError,{ maximumAge:Infinity, timeout:0 });
					break;
				default:
					$('#geo_note div').empty().append('<p class="error">Unknown error. Try again later.');
				break;
			}
		},
		initAutoComplete : function()
		{
			
			$.ui.autocomplete.prototype._renderItem = function (ul, item) {
				var re = new RegExp('('+ this.term.replace(/\(/, '\\(').replace(/\)/, '\\)') +')', 'i');
				var t = item.label.replace(re, '<span class="autocomplete-highlight">$1</span>');
				return $( '<li></li>')
				.data( 'item.autocomplete', item)
				.append( '<a>'+ t +'</a>' )
				.appendTo( ul );
			};				
			oishUtil.autoCompleteLocation();
			oishUtil.autoCompleteKeyword();
		},
		autoCompleteKeyword: function() {
			
			$('form[name="searchFrm"] input[name="keywords"]').autocomplete({
					source: function(req, add) {
						//post request to server
						$.ajax({   url: '/tags/ajax/keyword_suggest',
							dataType: 'json',
							type: 'POST',
							data: { q: req},
							success: function(data) {
								// create array for response objects
								var suggestions = [];
				
								// process response
								$.each(data.keywords, function(i, val) {
									suggestions.push(val);
								});
				
								//pass array to callback
								add(suggestions);
							}
				
						});
			
			
					},
				
					minLength: 1
			});			
		},
		autoCompleteLocation: function() {
			$('form[name="searchFrm"] input[name="location"]').autocomplete({
					source: function(req, add) {
						//post request to server
						$.ajax({   url: '/zipcodes/ajax/cities_autocomplete',
							dataType: 'json',
							type: 'POST',
							data: { q: req},
							success: function(data) {
								// create array for response objects
								var suggestions = [];
				
								// process response
								$.each(data.cities, function(i, val) {
									suggestions.push(val);
								});
				
								//pass array to callback
								add(suggestions);
							}
						});

			
					},
					select: function(evt, ui) {
						$.ajax	
						
						var param = { loc : ui.item.value};
						$.ajax( {url: '/zipcodes/ajax/getLocationInfo', dataType: 'json', type: 'POST', data: param, success: function(jsonObj) {
											
												if (jsonObj.success == true) {
													Oish.uLng = jsonObj.zipcode.longitude;
													Oish.uLat = jsonObj.zipcode.latitude;
													Oish.uLocality = (jsonObj.zipcode.city_alias.indexOf('(') == -1) ? 
																		ucwords(jsonObj.zipcode.city_alias.toLowerCase()) : jsonObj.zipcode.city_alias;
													Oish.uRegion = jsonObj.zipcode.state;
													Oish.uCountry = 'US';
													Oish.uTimezone = jsonObj.zipcode.timezone;
													Oish.uZipcode = jsonObj.zipcode.zipcode;
													Oish.uDst = jsonObj.zipcode.dst;
													Oish.uTimezone = jsonObj.zipcode.timezone;
													Oish.locPrompt = 'true';
													Oish.gotLoc = 'true';
													Oish.uCity = jsonObj.zipcode.city;
													(jsonObj.zipcode.city_alias.indexOf('(') == -1) ? $('#location').val(Oish.uLocality +', '+ Oish.uRegion) 
															: $('#location').val(Oish.uLocality);
													oishUtil.cache.location = $('#location').val();
													oishUtil.updateGeoLocationSession();
													//oishUtil.updateNeighorCities();
												}
						}});
					},
					minLength: 0
			});
		},
		ignoreTimeChars : function(evt) {
			//console.log( evt.keyCode );
			
			var numLen = $(evt.currentTarget).val().length;				
			var KEYS = {
				DIGITS : [48,49,50,51,52,53,54,55,56,57],
				SHIFT : [16],
				DASH : [],
				ALLOWCHARS : [80,77,65,80,190,32],
				CTRLKEYS : [86,67,65,88],
				DELETECHAR : [8,46],					
				ALLOWED : [32,48,49,50,51,52,53,54,55,56,57,16,8,46,37,39,9,96,97,98,99,100,101,102,103,104,105,32,80,77,65,190]
			}


			if (evt.keyCode == 9 && evt.shiftKey) {
				return true;
			}
			
			
			if (($.inArray(evt.keyCode, KEYS.ALLOWCHARS) >= 0) && evt.shiftKey) {
				return true;
			}
		
			
			if (($.inArray(evt.keyCode, KEYS.CTRLKEYS) >= 0) && ((evt.keyCode == 224) || (evt.ctrlKey) || (evt.metaKey))) {
				return true;
			}
				
			if (evt.keyCode == 59 && evt.shiftKey != true) {
				return false;
			}
			
			if (($.inArray(evt.keyCode, KEYS.ALLOWED) == -1) || (evt.shiftKey == true)) {
				if (evt.keyCode != 59) {
					return false;
				} 
				
			}				
		},
		validateTimeInput : function(evt) {
			var elemInput = $(evt.currentTarget);
			if (!(elemInput.val().match(/^((([0]?[1-9]|1[0-2])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?( )?(am|pm))|(([0]?[0-9]|1[0-9]|2[0-3])(:|\.)[0-5][0-9]((:|\.)[0-5][0-9])?))$/i))) {
				elemInput.addClass('timeError');
				elemInput.siblings('.timeErrorTxt').text('Incorrect time format (hh:mm am/pm)');
				return false;
			} else {
				if (elemInput.hasClass('timeError')) {
					elemInput.removeClass('timeError');
					elemInput.siblings('.timeErrorTxt').text('');
				}
				return true;
			}	
		},
		searchSubmit: function(el) {
			if ($('#keywords').val() == oishUtil.defaults.keywordInput) {
				$('#keywords').val('');
			}
			if ($('#location').val() != oishUtil.cache.location) {
				Oish.gotLoc = 'false';
				oishUtil.updateGeoLocationSession();
			}
			return true;
		},
		voteReview: function(el) {
			var review_vote = $(el.currentTarget).attr('class');
			var review_id = $(el.currentTarget).parents('div.commentListing_ctner div.entry').attr('id').replace(/review_/, '');
			var params = { 
					vote : (review_vote == 'good') ? true : false,
					reviewId : review_id
			}
			
			$.ajax( { url: '/reviews/ajax/vote_review', type: 'POST', dataType: 'json', data: params, success: function(jsonObj){
							if (jsonObj.success == false) {	
								
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'error', 'message' : jsonObj.message }, function() { return false });
							} else {
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'notice', 'message' : jsonObj.message }, function() { return false });
								
								$($(el.currentTarget).parents()[0]).find('span.good span.total').empty().append(jsonObj.likes);
								$($(el.currentTarget).parents()[0]).find('span.bad span.total').empty().append(jsonObj.dislikes);
							}
				
						}
				}
			);
				
		},
		flagReview: function(el) {
			var review_id = $(el.currentTarget).parents('div.commentListing_ctner div.entry').attr('id').replace(/review_/, '');
			var params = { 
					contentType : 'review',
					contentId : review_id
			}		
			$.ajax( { url: '/flagged_contents/ajax/flag', type: 'POST', dataType: 'json', data: params, success: function(jsonObj){
							if (jsonObj.success == false) {	
								
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'error', 'message' : jsonObj.message }, function() { return false });
							} else {
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'notice', 'message' : jsonObj.message }, function() { return false });
								
							}
				
						}
				}
			);

		},
		addFavorites: function(el) {
			
			var params = { 
					restId : Oish.restaurantId
			}		
			$.ajax( { url: '/restaurants/ajax/add_favorites', type: 'POST', dataType: 'json', data: params, success: function(jsonObj){
							if (jsonObj.success == false) {	
								
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'error', 'message' : jsonObj.message }, function() { return false });
							} else {
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'notice', 'message' : jsonObj.message }, function() { return false });
								$('div.restaurant_detail div.restaurant_info p.favorite').empty().append('<a href="javascript:void(0);" title="Remove from Favorites" class="btn_removeFav">Remove from Favorites</a>');
								$('div.restaurant_detail div.restaurant_info a.btn_addFav').unbind('click', oishUtil.addFavorites);
								$('div.restaurant_detail div.restaurant_info a.btn_removeFav').click(oishUtil.removeFavorites);
							}
				
						}
				}
			);

		},
		removeFavorites: function(el) {
			
			var params = { 
					restId : Oish.restaurantId
			}		
			$.ajax( { url: '/restaurants/ajax/delete_favorites', type: 'POST', dataType: 'json', data: params, success: function(jsonObj){
							if (jsonObj.success == false) {	
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'error', 'message' : jsonObj.message }, function() { return false });
							} else {
								oishUtil.modalPopUp('/ajax/popupMsg', { msgType : 'notice', 'message' : jsonObj.message }, function() { return false });
								$('div.restaurant_detail div.restaurant_info p.favorite').empty().append('<a class="btn_addFav" title="Add to Favorite" href="javascript:void(0);">Add to Favorites</a>');
								$('div.restaurant_detail div.restaurant_info a.btn_removeFav').unbind('click', oishUtil.removeFavorites);
								$('div.restaurant_detail div.restaurant_info a.btn_addFav').click(oishUtil.addFavorites);
							}
				
						}
				}
			);

		},
		gaTrackEvents: function() {
			$('div#logo a').click(function() { _gaq.push(['_trackEvent', 'masthead', 'click', 'logo']); });
			$('div#account-header a#ac_logout').click(function() { _gaq.push(['_trackEvent', 'account-header', 'click', 'logout']); });
			if (Oish.moduleName == 'member') {
				$('div#account-header a[title="Oish.com"]').click(function(){ _gaq.push(['_trackEvent', 'account-header', 'click', 'home']) });
				$('div#account-header a[title="My Account"]').click(function() { _gaq.push(['trackEvent', 'account-header', 'click', 'My Account']); });
				$('div#account-header a[title="Add Restaurant"]').click(function(){ _gaq.push(['_trackEvent', 'account-header', 'click', 'Add Restaurant']) });
				$('div#account-header a[title="Contact"]').click(function() { _gaq.push(['trackEvent', 'account-header', 'click', 'Contact']); });
				$('div#account-header a[title="FAQ"]').click(function(){ _gaq.push(['_trackEvent', 'account-header', 'click', 'FAQ']) });
				$('div#account-header a[title="My Account"]').click(function() { _gaq.push(['trackEvent', 'account-header', 'click', 'My Account']); });
				
				$('div#main_nav a#mm_profile').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Profile']) });
				$('div#main_nav a#mm_favorites').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Favorites']) });
				$('div#main_nav a#mm_reviews').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Reviews']) });
				$('div#main_nav a#mm_friends').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Friends']) });
				$('div#main_nav a#mm_mail').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Mail']) });
				$('div#main_nav a#mm_editaccount').click(function(){ _gaq.push(['_trackEvent', 'user_profile', 'click', 'Edit Account']) });
			} else {
				if (Oish.isLogin == true) {
					$('div#account-header a#o-bar-my-account').click(function() { _gaq.push(['_trackEvent', 'account-header', 'click', 'My Account']); });
				} else {
					$('div#account-header a#o-bar-login').click(function() { _gaq.push(['_trackEvent', 'account-header', 'click', 'login']); });
					$('div#account-header a#o-bar-create').click(function() { _gaq.push(['_trackEvent', 'account-header', 'click', 'create a profile']); });

				}
				$('div#mainmenu a#mm_home').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'home']); });
				$('div#mainmenu a#mm_business').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'Business Owners']); });
				$('div#mainmenu a#mm_about').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'About']); });
				$('div#mainmenu a#mm_faq').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'FAQ']); });
				$('div#mainmenu a#mm_contact').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'Contact']); });
				$('div#mainmenu a#mm_addRestaurant').click(function() { _gaq.push(['_trackEvent', 'mainmenu', 'click', 'Add Restaurant']); });
			}			
		},
		fbLogin : function(evt)
		{
			$.ajax( {url: '/ajax/facebook_login', dataType: 'json', type: 'POST', success: function(jsonObj) {
						
							if (jsonObj.success == true)
							{
								var accountHeader = (Oish.methodName == 'member') ? jsonObj.user_header_html : jsonObj.header_html;
								$('div#wrapper div#account-header').empty().append(accountHeader);	
								Oish.fbId = jsonObj.facebook_id;
								Oish.uid = jsonObj.uid;
								Oish.userName = jsonObj.userName;
								Oish.isLogin = true;
							}
			
						}
					});
		},
		sharePopup : function(evt)
		{
			
			var elem = $(evt.currentTarget);
			var elemParent = elem.parent();
			$.ajax( {url: '/ajax/sharePopup', dataType: 'json', type: 'POST', data: {shareType : evt.data.shareType, contentId: evt.data.contentId}, success: function(jsonObj) {
					
							if (jsonObj.success == true) {
								var distInput = jsonObj.html;
								oishUtil.displaySharePopUp(distInput, evt);
								$('div.sharePopUp .shareCtner ul li a').each(function(idx, elem){
									var medium = $(elem).attr('class');
									var redirecter = $(elem).attr('href');
									
									$(elem).click(function(el) {
										el.preventDefault();
										_gaq.push(['_trackEvent', 'share-'+ evt.data.shareType.toLowerCase(), 'click', evt.data.contentId]);
										var winWidth = 0;
										var winHeight = 0;
										switch(medium) {
											case 'twitter':
												winWidth = 980;
												winHeight = 300;
												break;
											case 'stumbleupon':
												winWidth = 800;
												winHeight = 400;
												break;
											case 'digg':
												winWidth = 980;
												winHeight = 400;
												break;
											default:
												winWidth = 600;
												winHeight = 400;
												break;
										}
										window.open(redirecter, '_BLANK', 'width='+ winWidth +',height='+ winHeight +',scrollbars=yes,toolbar=no,menubar=no,resizable=yes');
										return false;
									});
									
								});
								
							}
						}
					});	
					_gaq.push(['_trackEvent', 'share-content', 'click', evt.data.shareType]);
			
		},
		displaySharePopUp: function(elem,evt) {
			if ($('div.sharePopUp').is('*')) {
				oishUtil.closeSharePopup();
			}
			$('body').append(elem);
			var elemPos = $(evt.currentTarget).offset();
			var elemWidth = $('div.sharePopUp').width();
			var elemLeft = ((elemPos.left + elemWidth) > $(window).width()) ? ($(window).width() - elemWidth - 50) : elemPos.left;

			$('div.sharePopUp').css({ position: 'absolute',
												zIndex:	10000,
												top : (elemPos.top + 20)+ 'px',
												left : elemLeft + 'px'}).fadeIn();
			$(window).bind('resize', oishUtil.positionSharePopup);	
		
			$('div.sharePopUp a[title="Close"]').bind('click', oishUtil.closeSharePopup);
		},
		positionSharePopup: function(evt) {
			var pos = $('div.sharePopUp').position();
			var elemWidth = $('div.sharePopUp').width();
			var elemLeft = ((pos.left + elemWidth) > $(window).width()) ? ($(window).width() - elemWidth - 30) : pos.left;
			$('div.sharePopUp').css({ top: (pos.top + 20) + 'px', left: elemLeft + 'px' });			
		},
		closeSharePopup: function() {
			$(window).unbind('resize', oishUtil.positionSharePopup);
			$('div.sharePopUp a[title="Close"]').unbind('click', oishUtil.closeSharePopup);
			$('div.sharePopUp').remove();
		},
		fbInit : function()
		{
		      FB.init({
		                appId: oishFb.appId,
		                status: true,
		                cookie: true,
		                xfbml: true
		        });

		}
		
		
	}


	$(window).load(oishUtil.init);
//  })
})(jQuery);
