/**
 *
 * Bazomb! Javascript
 *
**/



/* Stuff to do once the page has loaded...
**********************************************************************/
$(function () {
	
	// init drop-down nav
	initNavbar();
	
	$('#resultToggles select').change( function(ev) {
		goTo( $(this).val() );
	});
	
	//
	// init AutoComplete
	//
	
	// for location search
	$("input.autoCompleteField[name='location'], input#suggestZip").autocomplete({
		serviceUrl: 'support/locationAutoComplete.json',
		minChars: 1,
		maxHeight: 400,
		width: 300,
		onSelect: function (value, data) {}
	});
	
	// for category search
	$("input.autoCompleteField[name='category']").autocomplete({
		serviceUrl: 'support/categoryAutoComplete.json',
		minChars: 1,
		maxHeight: 400,
		width: 300,
		onSelect: function (value, data) {}
	});
	
	
	
	//
	// category search form
	//	
	var defaultText = 'Leave empty to see all offers';
	var $categoryField = $('form#search input#category');
	
	// show default text when field is empty
	$categoryField.focus(function () {
		var $this = $(this);
		var val = $this.val();
		
		if (val == defaultText) {
			$this.val('');
			$this.removeClass('empty');
		}
	}).blur(function () {
		var $this = $(this);
		var defaultText = 'Leave empty to see all offers';
		var val = $this.val();
		
		if (!val) {
			$this.addClass('empty');
			$this.val(defaultText);
		}
	}).blur();
		
	// remove default text when submitting
	$('form#search input#submitButton').click(function () {
		var val = $categoryField.val();
		
		if (val == defaultText) {
			$categoryField.val('');
		}
	});
	
	//
	// suggest a city default text
	//
	var suggestCityLocationText = "Enter a City, State or Zip";
	var suggestCityEmailText    = "Enter your Email address (optional)";
	
	$('#suggestZip').focus(function () {
		var $this = $(this);
		var val = $this.val();
		
		if (val == suggestCityLocationText) {
			$this.val('');
			$this.removeClass('empty');
		}
	}).blur(function () {
		var $this = $(this);
		var defaultText = suggestCityLocationText;
		var val = $this.val();
		
		if (!val) {
			$this.val(defaultText);
			$this.addClass('empty');
		}
	}).blur();
	
	$('#suggestEmail').focus(function () {
		var $this = $(this);
		var val = $this.val();
		
		if (val == suggestCityEmailText) {
			$this.removeClass('empty');
			$this.val('');
		}
	}).blur(function () {
		var $this = $(this);
		var defaultText = suggestCityEmailText;
		var val = $this.val();
		
		if (!val) {
			$this.val(defaultText);
			$this.addClass('empty');
		}
	}).blur();
	
	$('#suggestZip, #suggestEmail').each(function(ev) {
		if( this.value == suggestCityLocationText || this.value == suggestCityEmailText ) {
			$(this).addClass('empty');
		} 
	});
	
	$('form#suggestCityForm').bind('submit', function(ev) {
		var val_email  = $('#suggestEmail').val();
		var val_zip    = $('#suggestZip').val();
		var $suggestZipErr   = $('.suggest-zip-error');
		var $suggestCheckErr = $('.suggest-checkbox-error');
		var $suggestEmailErr = $('.suggest-email-error');
		var isOk = true;
		if( val_email == suggestCityEmailText ) {
			val_email = '';			
		}
		//--
		$suggestZipErr.hide();
		$suggestCheckErr.hide();
		
		if( val_zip == '' || val_zip == suggestCityLocationText ) {
			$suggestZipErr.show();
			isOk = false;
		}
		//-- check errors
		if( !$('#isMerchantInterest').attr('checked') && !$('#isConsumerInterest').attr('checked') ) {
			$suggestCheckErr.show();
			isOk = false;
		}
		else {
			$suggestCheckErr.hide();
		}		
		//-- check email
		if( val_email != '' && val_email.search(/^\w+((-\w+)|(\.\w+))*\@[A-Za-z0-9]+((\.|-)[A-Za-z0-9]+)*\.[A-Za-z0-9]+$/) == -1 ) {
			$suggestEmailErr.show();
			isOk = false;
		}
		else {
			$suggestEmailErr.hide();
		}
		if(!isOk){
			return false;
		}
		$('#suggestEmail').val(val_email);
		
		return true;
	});
	
	$('#locationRefine').bind( 'click', function(ev) {
		$('#refineLocation').val('1');
		$('#locationSwitchForm').submit();
	} );
	
	$('#locationSwitchForm').bind( 'submit' , function() {
		var currLocation = location.href;
		if( currLocation.match('offers-list.html') || currLocation.match('retailers-list.html') ) {
			this.action = currLocation;
			return true;
		}
		this.action = 'home.html';
		return true;
	});
	
	// make search filter dropdowns change pages
	$('select.auto-refresh').change(function () {
		goTo($(this).val());
	});
	
	// save coupon buttons
	$('.saveCouponButton').click(function () {
		
		var $this = $(this);
		var offerId    = $this.parents('.offer').attr('offerId');
		var locationId = $this.parents('.offer').attr('locationId');
		
		saveCoupon.call(this, locationId, offerId);
		
		return false;
	});
	
	// remove coupon buttons
	$('.removeCouponButton').click(function () {
		var $this = $(this);
		var $offer = $this.parents('.offer');
		
		var offerId = $offer.attr('offerId');
		var locationId = $offer.attr('locationId');
		
		removeCoupon.call(this, locationId, offerId);
		
		return false;
	});
	
	
	
	// pagination bar hovering
	$('div.paginationBar span.link').hover(
		function () {
			$(this).addClass('hover');
		},
		function () {
			$(this).removeClass('hover');
		}
	);
	//
	//var isFreshBoomAd = $.cookie('isFreshBoomAd');
	//alert('current page cookie: ');
	// alert('Fresh Boom Ad: ' + $.cookie('isFreshBoomAd'));
	// show Mega Boom if necessary
	if (window.freshBoom ) {
		megaBoom(window.freshBoom);
	}
	
	// offer bubbles / retailer bubbles
	oBubbles.init();
	rBubbles.init();
	
	// init Ads
	adRotator.init();
});





/* FUNCTIONS
**********************************************************************/

/**
 * Fetches Featured Sponsor Ads, and creates an animated "Ad Parade".
 */
function makeAdParade() {
	
	$.ajax({
		url: 'support/getFeaturedSponsorAds.json',
		dataType: 'json',
		cache: false,
		data: {},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			// do nothing, ad area is hidden by default
		},
		success: function (text) {
			var countRows = 0;
			var navControlHtml = '';
			var html = '';
			var ad;
			
			//
			// build the HTML
			//
			for (var i=0; i<text.ads.length; i++) {
				ad = text.ads[i];
				
				// first slide
				if (i%4 == 0) {
					html += '<div>';
				}
				
				// middle slides
				html += '<div class="featuredBusinessAd" align="center" style="float:left;">';
				html += '<a href="adClick.do?locationId='+ad.locationId+'&retailerId='+ad.retailerId+'&adId='+ad.adId+'&siteSection=parade"><img border="0" src="' + ad.image + '" /></a>';
				html += '</div>';
				
				// last slide
				if (i%4 == 3 || i == text.ads.length-1) {
					countRows++;
					navControlHtml += '<span class="jFlowControl">No '+ countRows+' </span>';
					html += '<div class="clear" /></div>';
				}
			}
			
			//
			// create the parade
			//
			if (html != '') {
				$('.mySponsorsController').html(navControlHtml);
				$('#sponsorsBoxBody').html(html);
				
				$('#sponsorsBox').show();
				
				$('.mySponsorsController').jFlow({
					slides: '#sponsorsBoxBody',
					width: '798px',
					height: '114px',
					easing: 'easeInOutCubic',
					duration: 500,
					autoScroll: true,
					autoScrollDelay: 4000
				});
			}
		}
	});
}

/**
 * Launches the Print Voucher dialog.
 */
var printVoucher = function (orderId) {
	$('#print-voucher-dialog').dialog('destroy');
	$('#print-voucher-dialog .printVoucherContent').load( 'mbd-voucher-confirmation.html #voucherConfirmationContent', { orderId:orderId } );
	$( "#print-voucher-dialog" ).dialog({
		dialogClass: 'printvoucher',
		autoOpen: true,
		height: 400,
		width: 400,
		modal: true,
		buttons: { 
			Print: function() { 
				$(this).dialog("close");
				window.open("printVoucher.do?orderId=" + orderId, '_blank');
			},
			Cancel: function() { 
				$(this).dialog("close"); 
			} 
		}
	});
	return false;
}

/**
 * Launches the Print Coupon dialog.
 */
var printCoupon = function (id) {
	
	var $dialog     = $('div#printCouponDialog').clone();
	var $offer      = $('div#offerList div.offer[offerLocationId=' + id + ']');
	var siteSection = $('body').attr('siteSection');
	var $printBtn   = $('.printCouponButton', $dialog);
	var $cancelBtn  = $('.cancelButton'     , $dialog);
	var $saveLink   = $('.saveCouponLink'   , $dialog);
	var locationId  = $('div.offer[offerLocationId=' + id + ']').attr('locationId');
	var offerId     = $('div.offer[offerLocationId=' + id + ']').attr('offerId');
	var $content = $('.printCouponContent', $dialog);
	var contentHtml  = $('div.offerBubble[offerLocationId=' + id + '] .offerBubbleContent').html();
	$content.html( contentHtml );

	
	// event handler for Cancel button
	$cancelBtn.click(function () {
		$.unblockUI();
		return false;
	});
	
	// event handler for Print button
	$printBtn.click(function () {
		$.unblockUI(); // unblock the UI after clicking print
		return true; // let the event propogate so the href is used
	});
	
	// event handler for Save Coupon link
	$saveLink.unbind('click').click(function (e) {
		e.preventDefault();
		$.unblockUI();
		if( $offer.length == 0 ) {
			$offer = $('div#offer div.offer[offerLocationId= '+ id +']');
		}
		$offer.find('.saveCouponButton').click(); // trigger the offer's Save button
	});

	// set the print button's destination
	$printBtn.attr('href', 'printCoupon.do?offerId=' + offerId + '&locationId=' + locationId + '&siteSection=' + siteSection);
	
	
	// if the offer can no longer be printed, we want to change the message and remove the coupon...
	if ($offer.attr('expired') || $offer.attr('exhausted')) {
		
		$printBtn.remove(); // get rid of the Print button
		$cancelBtn.click(function () {
			$offer.find('.removeCouponButton').click(); // trigger the offer's Remove button
		});
		
		if ($offer.attr('expired')) {
			// offer has expired
			$('div.content', $dialog).html('Sorry, this offer expired on ' + $offer.attr('expired') + '.');
		} else if ($offer.attr('exhausted')) {
			// offer has been exhausted
			$('div.content', $dialog).html('Sorry, this offer was limited to ' + $offer.attr('exhausted') + ' customers and is no longer available.');
		}
	}
	
	
	// show the confirmation dialog
	$.blockUI({
		message: $dialog,
		css: {
			width: '400px',
			cursor: 'default',
			top:'10%'
		},
		overlayCSS: {
			backgroundColor: '#000',
			opacity: '0.8'
		}
	});
}


/**
 * Ad Rotator module.
 */
var adRotator = function () {
	var url = 'support/getAd.json';
	var dims = {
		tower: {
			w: 120,
			h: 600
		},
		sponsor: {
			w: 167,
			h: 90
		},
		banner: {
			w: 728,
			h: 90
		}
	};
	
	function getAd(params, repeatInterval) {
		//console.log('getAd(' + params.zone + ', ' + repeatInterval + ') @ ' + new Date().toTimeString());
		
		$.extend(params, {
		    retailerId  : window.retailerId     || ''
		,   locationId  : window.locationId     || ''
		,   location    : window.searchLocation || ''
		,   category    : window.searchCategory || ''
		,   siteSection : $('body').attr('siteSection')
		});
		
		// don't fetch tower ads for certain pages
		if (params.zone == 'tower' && window.noTowerAd) {
			return false;
		}
		
		$.ajax({
			url: url,
			dataType: 'json',
			cache: false,
			data: params,
			error: function (XMLHttpRequest, textStatus, errorThrown) {
				//
			},
			success: function (data, textStatus) {
				var zone = params.zone;
				var $zone = $('div.ad_' + zone);
				var img = new Image();
				
				if (!data.image) {
					// if for some reason there is no image info in the data,
					// show a pretty pattern instead.
					$zone.empty().append('<img src="images/temp_' + zone + '.gif" height="' + dims[zone].h + '" width="' + dims[zone].w + '">');
					
					// loop
					if (repeatInterval) {
						window.setTimeout(function () {
							getAd(params, repeatInterval);
						}, repeatInterval);
					}
					
				} else {
					// if this ad is already showing, don't show the transition, and
					// don't mark is as a "view"
					if (data.image == $zone.find('img').attr('src')) {
						// loop
						if (repeatInterval) {
							window.setTimeout(function () {
								getAd(params, repeatInterval);
							}, repeatInterval);
						}
					} else {
						var siteSection = $('body').attr('siteSection');
						
						var linkTarget = '_self';
						if( data.target == '_blank' && data.isUrl == 'true' ) {
							linkTarget = '_blank';
						}
						
						// load the image first, then show it
						img.onload = function () {
							// Only do the fade if there is a legit banner already loaded.
							// We can judge that by checking if there's a link tag present.
							if ($('a', $zone).length > 0) {
								$zone.each(function () {
									
									$(this).fadeOut(500, function () {
										
										$(this).empty()
										.append('<a href="' + data.link + '" target="' + linkTarget + '"><img src="' + data.image + '" height="' + dims[zone].h + '" width="' + dims[zone].w + '"></a>')
										.fadeIn(500, function () {
											// make sure this callback is only executed once
											if ($zone.index(this) == $zone.length - 1) {
												
												// tell the server we have "viewed" this ad
												$.get('conduit/track/adView.json?adId=' + data.id + '&locationId=' + data.locationId + '&siteSection=' + siteSection);
												
												// loop
												if (repeatInterval) {
													window.setTimeout(function () {
														getAd(params, repeatInterval);
													}, repeatInterval);
												}
											}
										});
									});
								});
							} else {
								$zone.empty().append('<a href="' + data.link + '" target="' + linkTarget + '"><img src="' + data.image + '" height="' + dims[zone].h + '" width="' + dims[zone].w + '"></a>');
								
								// tell the server we have "viewed" this ad
								$.get('conduit/track/adView.json?adId=' + data.id + '&locationId=' + data.locationId + '&siteSection=' + siteSection);
								
								// loop
								if (repeatInterval) {
									window.setTimeout(function () {
										getAd(params, repeatInterval);
									}, repeatInterval);
								}
							}
						};
						img.src = data.image;
					}
				}
			}
		});
	}
	
	return {
		init: function () {
			// Home page has no ads at all.
			// Dashboard page has no tower ad.
			
			if (window.pageId != 'home') {
				// Sponsor Ad (every 60s)
				getAd({
					zone: 'sponsor'
				}, 60000);
				
				// Banner Ad (every 60s)
				getAd({
					zone: 'banner'
				}, 60000);
				
				if (window.pageId != 'dashboard') {
					// Tower Ad (only once)
					getAd({
						zone: 'tower'
					});
				}
			}
		}
	}
}();


/**
 * Offer Bubbles module.
 */
var oBubbles = function () {
	//
	var settings = {
		//showDelay: 1000,
		showDelay: 0,
		hideDelay: 0
	};
	var $offers;
	var $activeBubble;
	var timerId;
	
	function show(offer) {
		
		var $offer     = $(offer);
		var offerId    = $offer.attr('offerId');
		var locationId = $offer.attr('locationId');
		var siteSection = $('body').attr('siteSection');
		var $bubble = $activeBubble = getOfferBubble(offerId + '-' + locationId);

		// adjust position
		position($offer, $bubble);
		
		// fix zIndex problem in IE
		fixZ($offer);
		
		// show
		timerId = setTimeout(function () {
			$bubble.show();
			
			// tell the server we have "viewed" this bubble
			$.get('conduit/track/offerClick.json?locationId='+locationId+'&offerId=' + offerId + '&siteSection=' + siteSection);
			
		}, settings.showDelay);
	};
	
	function hide(offer, e) {
		var $bubble = $activeBubble;
		
		// canel timer
		clearTimeout(timerId);
		
		// hide
		if ($activeBubble) { // fix: JS error when $bubble goes missing.
			$bubble.hide();
		}
		
		$activeBubble = null;
	};
	
	function getOfferBubble(offerLocationId) {
		var $bubble = $('div.offerBubble[offerLocationId=' + offerLocationId + ']');
		
		return $bubble;
	};
	
	function position($offer, $bubble) {
		var oHeight = $offer.height();
		var bHeight = $bubble.height();
		var offset = 15; // this offsets the drop shadow
		var adjustment;
		
		adjustment = Math.round((bHeight - oHeight) / 2);
		adjustment -= offset;
		
		$bubble.css('top', '-' + adjustment + 'px');
	};
	
	function fixZ($offer) {
		// The bubble will appear behind other offers unless
		// we raise the current offer above the others.
		$offers.css('z-index', 1);
		$offer.css('z-index', 2);
	};
	
	
	
	return {
		init: function () {
			$offers = $('div.offer');
			
			// trigger the bubble when hovering over offer image:
			$('div.image', $offers).hover(
				function () {
					var offer = $(this).parents('div.offer');
					show(offer);
				},
				function () {
					var offer = $(this).parents('div.offer');
					hide(offer);
				}
			);
		}
	}
}();


/**
 * Retailer Bubbles module.
 */
var rBubbles = function () {
	//
	var settings = {
		showDelay: 1000,
		hideDelay: 0
	};
	var $activeBubble;
	var timerId;
	
	function show($bubble, e) {
		$activeBubble = $bubble;
		
		// adjust position
		position($bubble, e);
		
		// show
		timerId = setTimeout(function () {
			$bubble.show();
		}, settings.showDelay);
	};
	
	function hide($bubble) {
		// canel timer
		clearTimeout(timerId);
		
		// hide
		if ($activeBubble) { // fix: JS error when $bubble goes missing.
			$bubble.hide();
		}
		
		$activeBubble = null;
	};
	
	function position($bubble, e) {
		var x = e.pageX;
		var y = e.pageY;
		var bHeight = $bubble.height();
		var offset = 15; // this offsets the drop shadow
		var adjustment;
		
		adjustment = Math.round(bHeight / 2);
		adjustment -= offset;
		
		$bubble.css({
			'top': y - adjustment + 'px',
			'left': x + 100 + 'px'
		});
	};
	
	
	return {
		init: function () {
			// trigger the bubble when hovering over business name link:
			$('div#resultList a').hover(
				function (e) {
					var $bubble = $(this).siblings('div.retailerBubble');
					show($bubble, e);
				},
				function () {
					var $bubble = $(this).siblings('div.retailerBubble');
					hide($bubble);
				}
			);
		}
	}
}();


/**
 * Drop-down Nav functionality.
 */
function initNavbar() {
	//
	$('ul.subnav').each(function () {
		$(this).children('li:first').addClass('first');
	});
	
	// Hover action for Nav Items (with subnavs)
	$("ul.nav > li:has(ul.subnav)").hover(
		function () {
			var $this = $(this);
			
			$this.addClass("hover");
			$this.children("ul.subnav").show();
		},
		function () {
			var $this = $(this);
			$this.removeClass("hover");
			$this.children("ul.subnav").hide();
		}
	);
	
	// Hover action for Subnav Items
	$("ul.subnav > li").hover(
		function () {
			$(this).addClass("subnavHover");
		},
		function () {
			$(this).removeClass("subnavHover");
		}
	);
	
	// Click action for Nav/Subnav Items
	$("ul.nav li").click(function (e) {
		var link = $(this).find('a').attr('href');
		
		e.stopPropagation();
		goTo(link);
	});
	
	// Stop the <a>'s click event from triggering the <li>'s click event
	$("ul.nav a").click(function (e) {
		e.stopPropagation();
	});
}


/**
 * Shows the Large Boom Ad Overlay.
 */
function megaBoom(adPath) {
	var img = new Image();
	
	img.onload = function () {
		var size = {
			w: this.width,
			h: this.height
		};
		
		$.blockUI({
			//message: $('<img src="images/temp_megaboom.gif">'),
			message: $('<img src="' + adPath + '" height="' + size.h + '" width="' + size.w + '">'),
			css: {
				top:  ($(window).height() - size.h) /2 + 'px', 
				left: ($(window).width() - size.w) /2 + 'px', 
				width: size.w + 'px',
				border: 'none'
			},
			overlayCSS:  { 
				backgroundColor: '#000',
				opacity: '0.9'
			}
		}); 
		setTimeout($.unblockUI, 3000);
	}
	img.src = adPath;
}


/**
 * Saves a Coupon to the Drawer,
 * then disables the save button so it can't be used again.
 */
function saveCoupon(locationId, offerId) {
	// *this should be mapped to the buttonthat triggered this function.
	var $this = $(this);
	var offerLocationId = offerId + '-' + locationId;

	var offerData = $('div[offerLocationId='+offerLocationId+']');
	var siteSection = $('body').attr('siteSection');
	
	$.ajax({
		url: 'conduit/drawer/addOffer.json',
		dataType: 'json',
		cache: false,
		data: {
			locationId  : locationId
		,   offerId     : offerId
		,   siteSection : siteSection
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//
		},
		success: function (data, textStatus) {
			if (data.header && data.header.success) {
				// replace button image, remove link
				$this.find('img')
					.attr('src', 'images/circus_btn_couponsaved.gif')
					.appendTo($this.parent())
					.removeClass('saveCouponButton')
					.addClass('saveCouponButtonDisabled');
				$this.remove();
				
				// show Growl-style notification
				$.blockUI({
					message: $('<div class="growlUI"><h1>Coupon saved.</h1><h2><a href="saved-offers-list.html">Click here</a> to view your saved coupons.</h2></div>'),
					fadeIn: 500, 
					fadeOut: 500, 
					timeout: 5000, 
					showOverlay: false, 
					centerY: false, 
					css: { 
						width: '325px',
						top: '10px',
						left: '',
						right: '10px',
						border: 'none',
						padding: '5px',
						backgroundColor: '#000',
						'-webkit-border-radius': '10px',
						'-moz-border-radius': '10px',
						opacity: '1',
						color: '#fff'
					}
				});
			}
		}
	});
	
}


/**
 * Removes a Coupon from the Drawer.
 */
function removeCoupon(locationId, offerId) {
	// *this should be mapped to the buttonthat triggered this function.
	var $this = $(this);
	
	$.ajax({
		url: 'conduit/drawer/removeOffer.json',
		dataType: 'json',
		cache: false,
		data: {
		    offerId    : offerId
		,   locationId : locationId
		},
		error: function (XMLHttpRequest, textStatus, errorThrown) {
			//
		},
		success: function (data, textStatus) {
			if (data.header && data.header.success) {
				// replace button image, remove link
				$this.parents('div.offer').animate({
					opacity: 0
				}, 250, function () {
					$(this).animate({
						height: 0
					}, 400, function () {
						$(this).remove();
					});
				});
				
				// change coupon count text
				var couponCount = $('div#resultText > span.keyword').text();
				
				if (couponCount == 'one') {
					$('div#resultText').html('You have no saved coupons');
				} else if (couponCount == 2) {
					$('div#resultText').html('You have <span class="keyword">one</span> saved coupon');
				} else {
					couponCount--;
					$('div#resultText').html('You have <span class="keyword">' + couponCount + '</span> saved coupons');
				}
				
				// show Growl-style notification
				$.blockUI({
					message: $('<div class="growlUI"><h1>Coupon removed.</h1></div>'),
					fadeIn: 500, 
					fadeOut: 500, 
					timeout: 5000, 
					showOverlay: false, 
					centerY: false, 
					css: { 
						width: '325px',
						top: '10px',
						left: '',
						right: '10px',
						border: 'none',
						padding: '5px',
						backgroundColor: '#000',
						'-webkit-border-radius': '10px',
						'-moz-border-radius': '10px',
						opacity: '1',
						color: '#fff'
					}
				});
			}
		}
	});
	
}


/**
 * Navigates to a URL, respecting the baseHref.
 */
function goTo(url) {
	//-- absolute paths
	if( startWith(url, "http:") || startWith(url, "https:") ) {
		window.location = url;
		return;
	}
	window.location = baseHref(url);
}


/**
 * Applies the base href to a url, if applicable.
 */
function baseHref(loc) {
	// loc is the relative path your wish to redirect to
	var b = document.getElementsByTagName('base');
	if (b && b[0] && b[0].href) {
		loc = b[0].href + loc;
	}
	return loc;
}


/**
 * Navigates back one entry in the user's history, or else
 * goes home if there is no history.
 */
function backOrHome() {
	if (window.history.length > 1) {
		window.history.go(-1);
	} else {
		window.location = 'home.html';
	}
}


/*
 * ???
 */
function startWith(str, startStr) {
	if( str.length < startStr.length ) {
		return false;
	}
	var part = str.substring(0, startStr.length );
	if( part == startStr ) {
		return true;
	}
	return false;
}

$(function() {
	var LocationSwitch = function() {
		var view = {};
		
		var settings = {
			'txtLocationPrompt': 'Enter a city name',
			'btnSaveTooltip': {
				'empty': 'Type a city name in the box, then click this button to find deals there.',
				'filled': 'Click this button to see deals in '
			}
		};
		
		function initialize() {
			setEventListeners();
		}
		
		function setEventListeners() {
			
			$('#location #change').toggle(
				function() {
					$('#locationSwitchDiv').show();
					$('#txtLocation').val($('#location .locationText').text());
					$('#txtLocation').focus();
				},
				function() {
					$('#txtLocation').blur();
					$('#locationSwitchDiv').hide();
				}
			);
			
			$('#txtLocation').focus(function () {
				var val = $(this).val();
				$(this).removeClass('empty');
				if ($.trim(val) == '') {
					$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.empty)
					$('#saveBtnWrapper .btnDimmer').show();
					$('#saveBtnWrapper #saveButton').attr('disabled', 'disabled');
					$(this).val(settings.txtLocationPrompt);
					$(this).addClass('empty');
				}
				else {
					$('#txtLocation').select();
					$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.filled + val + '.');
				}
				
			}).blur(function () {
				var val = $(this).val();
				if ($.trim(val) == '') {
					$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.empty)
					$('#saveBtnWrapper .btnDimmer').show();
					$('#saveBtnWrapper #saveButton').attr('disabled', 'disabled');
					$(this).val(settings.txtLocationPrompt);
					$(this).addClass('empty');
				}
				else {
					$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.filled + val + '.');
				}
				
			}).keyup(function() {
				var val = $(this).val();
				$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.filled + val + '.')
				$('#saveBtnWrapper .btnDimmer').hide();
				$('#saveBtnWrapper #saveButton').removeAttr('disabled');
				chkEmptyLocation();
			});
			
			$('#saveButton').click(function() {
				var val = $('#txtLocation').val();
				if (val == settings.txtLocationPrompt) {
					$('#txtLocation').val('');
				}
				if (($.trim(val)) == '') {
					$('#txtLocation').addClass('field-error');
					
					$('#txtLocation').one('focus', function () {
						$(this).removeClass('field-error');
					});
					$('#txtLocation').one('keydown', function () {
						$(this).removeClass('field-error');
					});
					
					return false;
				}
				return true;
			});
		}
		
		function chkEmptyLocation() {
			if (($.trim($('#txtLocation').val())) == '') {
				$('#saveBtnWrapper').attr('title', settings.btnSaveTooltip.empty)
				$('#saveBtnWrapper .btnDimmer').show();
				$('#saveBtnWrapper #saveButton').attr('disabled', 'disabled');
				$(this).val(settings.txtLocationPrompt);
				$(this).addClass('empty');
			}
		}
		
		return {
			init: function(){initialize()}
		}
	}().init();
})

