window.log = function(){	
	arguments.callee = arguments.callee.caller;
	if(this.console) console.log( Array.prototype.slice.call(arguments) );
};
(function(b){
	function c(){}
	for(var d="assert,count,debug,dir,dirxml,error,exception,group,groupCollapsed,groupEnd,info,log,markTimeline,profile,profileEnd,time,timeEnd,trace,warn".split(","),a;a=d.pop();)b[a]=b[a]||c
})(window.console=window.console||{});


function toggleStyleClass( selected, similar, cls ){
	$(similar).removeClass(cls);
	$(selected).addClass(cls);
}

(function(window,undefined){
	var nUA = navigator.userAgent.toLowerCase();
	if ((jQuery.browser.safari && !(/chrome/.test(nUA)) && (/safari/.test(nUA)))){
		//disabled for safari :(		
		return false;
	}

	var History = window.History,
	$ = window.jQuery,
	document = window.document;
	
	if (!History || !History.enabled ) {
		log("History.js disabled");
		return false;
	}
	
	$(function(){

		var	$content = $(".content").filter(':first'),
		$footer = $("#footer_container"),
		$headerImage = $("#header_container #header_image"),
		$breadcrumb = $("#breadcrumb"),
		contentNode = $content.get(0),
		$body = $(document.body),
		
		rootUrl = History.getRootUrl(),

		scrollOptions = {
			duration: 800,
			easing:'swing'
		};

		State = History.getState(),		
		
		$.expr[':'].internal = function(obj, index, meta, stack){
			var
			$this = $(obj),
			url = $this.attr('href')||'',
			isInternalLink;
			isInternalLink = url.substring(0,rootUrl.length) === rootUrl || url.indexOf(':') === -1;
			return isInternalLink;
		};

		var documentHtml = function(html){
			var result = String(html)
			.replace(/<\!DOCTYPE[^>]*>/i, '')
			.replace(/<(html|head|body|title|meta|script)([\s\>])/gi,'<div class="document-$1"$2')
			.replace(/<\/(html|head|body|title|meta|script)\>/gi,'</div>');
			return result;
		};

		$.fn.ajaxify = function(){
			var $this = $(this);
			$this.find('a.ajaxy').click(function(event){				
				if ( event.which == 2 || event.metaKey ) {
					return true;
				}
				event.preventDefault();
				var $this = $(this),url = $this.attr('href'),title = $this.attr('title')||null;
				History.pushState(null,title,url);
				
				return false;
			});
			return $this;
		};

		$body.ajaxify();

		$(window).bind('statechange',function(){
			var
			State = History.getState(),
			url = State.url,
			relativeUrl = "/" + url.replace(rootUrl,'');

			$body.addClass('loading');

			if ( !$.browser.msie ) {
				$content.animate({
					opacity:0
				},500);
			}
			
			$.ajax({
				url: relativeUrl,
				data: {
					ajaxified:1
				},
				success: function(data, textStatus, jqXHR){
					var
					$data = $(documentHtml(data)),
					$dataBody = $data.find('.document-body:first'),
					$dataContent = $dataBody.find(".content").filter(':first'),
					$dataFooter = $dataBody.find('#footer_container'),
					$dataBreadcrumb = $dataBody.find('#breadcrumb'),
					$menuChildren,
					contentHtml,
					$scripts;

					$scripts = $dataContent.find('.document-script');
					$footerscripts = $dataFooter.find('.document-script');
					
					if ($footerscripts.length){
						if ( $scripts.length ) {
							$scripts = $.merge( $scripts, $footerscripts);
						} else {
							$scripts = $footerscripts;
						}
					}

					if ( $scripts.length ) {
						$scripts.detach();
					}
					
					contentHtml = $dataContent.html() || $data.html();
					if ( !contentHtml ) {
						document.location.href = url;
						return false;
					}

					$breadcrumb.html( $dataBreadcrumb.html() ).ajaxify();

					$headerImageContent = $dataBody.find('#header_container #header_image');
					if ($headerImageContent.length){
						$headerImage.html( $headerImageContent.html() );
					}
					
					$footer.html( $dataFooter.html() ).ajaxify();					

					if ( $.browser.msie ) {
						$content.html(contentHtml).ajaxify().show();
					} else {
						$content.stop(true,true);
						$content.html(contentHtml).ajaxify().css('opacity',100).show();
					}

					// Update the title
					document.title = $data.find('.document-title:first').text();
					try {
						document.getElementsByTagName('title')[0].innerHTML = document.title.replace('<','&lt;').replace('>','&gt;').replace(' & ',' &amp; ');
					} catch ( Exception ) {}

										
					// Add the scripts
					$scripts.each(function(){
						var $script = $(this);
						var scriptText = $script.text();						
						try {
							if (scriptText){
								var scriptNode = document.createElement('script');
								scriptNode.type = 'text/javascript';
								scriptNode.text = scriptText;
								$content.append( scriptNode );
							}
						} catch( Exception ){}
					});
				   
					$body.removeClass('loading');

					$('.social_links a[title]').qtip({
						position: {
							my: 'bottom center',  // Position my top left..
							at: 'top center' // at the bottom right of...
						}
					});

					if ( typeof window.pageTracker !== 'undefined' ) {
						window.pageTracker._trackPageview(relativeUrl);
					}
					
					return true;
				},
				error: function(jqXHR, textStatus, errorThrown){
					document.location.href = url;
					return false;
				}
			});

		});
	});

})(window);


$(function(){
	
	var $store_input = $("#store_locator_input input:first");
	var $store_head = $("#head_store_locator_container");
	
	var $job_input = $("#job_search_input input:first");
	var $job_head = $("#head_job_search_container");

	$store_input.attr('title',$store_input.val()).focus(function(){
		$store_head.addClass('focused');
		$(this).val( $(this).val() == $(this).attr('title') ? '' : $(this).val() );
	}).blur(function(){$(this).val( $(this).val() == '' ? $(this).attr('title') : $(this).val() );})

	$job_input.attr('title',$job_input.val()).focus(function(){
		$job_head.addClass('focused');
		$(this).val( $(this).val() == $(this).attr('title') ? '' : $(this).val() );
	}).blur(function(){$(this).val( $(this).val() == '' ? $(this).attr('title') : $(this).val() );})

	var openJobSearch = function(){		
		$job_head.find(".job_search_box").stop().animate({top:0});
		closeStoreLocator();
	}
	var closeJobSearch = function(){
		$job_head.removeClass('focused').find(".job_search_box").stop().animate({top:-165});
	}
	var checkCloseJobSearch = function(){
		if (!$job_head.hasClass('focused')) closeJobSearch();
	}

	var openStoreLocator = function(){
		$store_head.find(".store_locator_box").stop().animate({top:0});
		closeJobSearch();
	}
	var closeStoreLocator = function(){
		$store_head.removeClass('focused').find(".store_locator_box").stop().animate({top:-184});
	}
	var checkCloseStoreLocator = function(){
		if (!$store_head.hasClass('focused')) closeStoreLocator();
	}

	$('html').click(function() {
		closeStoreLocator();
		closeJobSearch();
	});

	$job_head.mouseenter(openJobSearch).mouseleave(checkCloseJobSearch).click(function(evt){
		evt.stopPropagation();
		openJobSearch();
	});
	$store_head.mouseenter(openStoreLocator).mouseleave(checkCloseStoreLocator).click(function(evt){
		evt.stopPropagation();
		openStoreLocator();
	});

	
	var lastXhr,cache = {};
	$store_input.autocomplete({
		appendTo: ".store_locator_box",
		minLength: 2,
		select: function( event, ui ) {
			if (ui.item.id){
				if (typeof HJStores != "undefined"){
					HJStores.selectStore( HJStores.getStoreIdxBy('id',ui.item.id),true );
				} else {
					window.location = "/stores?id="+ui.item.id;
				}
			}
			return false;
		},
		source: function( request, response ) {
			var term = request.term;
			/*if ( term in cache ) {
				response( cache[ term ] );
				return;
			}*/



			lastXhr = $.getJSON( "/component/hjstore/?task=findstore&ac=1" + ($("#stores_with_wifi #free_wifi").is(":checked") ? '&fwifi=1' : ''), request, function( data, status, xhr ) {
				//cache[ term ] = data;
				if ( xhr === lastXhr ) {
					response( data );
				}
			});
		}
	}).data( "autocomplete" )._renderItem = function( ul, item ) {
		item.value = item.id;
		return $( "<li></li>" ).data( "item.autocomplete", item ).append("<a>" + item.name + "</a>").appendTo( ul );
	};

	$('.social_links a[title]').qtip({
		position: {
			my: 'bottom center',  // Position my top left..
			at: 'top center' // at the bottom right of...
		}
	});
	
});

