/*
	Desktop CSS. Extends B object defined in script.js
*/

B.settings.context = "desktop";

B.tools.findAccordion = function(){
	var parents = $('li[data-role=collapsible]');
	parents.find('.sublist').hide();
	
	parents.live('click', function(e){
		if(!$(e.target).is('a') && !$(e.target).is('.sublist li')){
			$(this).find('.sublist').slideToggle();	
		}
		
	});
};

B.tools.tabButtonIcons = function(){
	$('.tab-button').append('<span class="ui-icon"></span>');
};

B.tools.modalBoxSetup = function(){
	return false;
	// $("a.login-link").overlay({
	// 
	// 			mask: 'black',
	// 			effect: 'apple'
	// 
	// 		/*
	// 			onBeforeLoad: function() {
	// 
	// 						// grab wrapper element inside content
	// 						var wrap = this.getOverlay().find(".overlay-inner");
	// 						
	// 						// keep the interactions in the frame
	// 						wrap.append('<iframe src="login.html"></iframe>');
	// 						
	// 						// load the page specified in the trigger
	// 						// wrap.find('iframe').find('body').load("/layout/templates/login.html #screen-login");
	// 						wrap.find('iframe').contents().find('body').load("/layout/templates/login.html #screen-login");
	// 					}*/
	// 		
	// 
	// 		});
};

B.tools.userNav = function(){
	$('.login-menu+ul').hide();
	$('.logged-in').hover(function(){
		$(this).find('ul').show();
		$(this).find('.login-menu').addClass('on');
		
	}, function(){
		$(this).find('ul').slideUp('fast', function(){
			$(".login-menu.on").removeClass('on');
		});
		//make sure there is no confirm logout left in the source
		if($(this).find('p.confirm').length){
			$(this).find('p.confirm').remove().end()
				.find('.logout').show();
		}
	});
	
	// keep the a active
	$('.user-nav').hover(function(){
		$('.login-menu').addClass('on');
	}, function(){
	});
};

B.tools.repositionFlashMessages = function(){
	if($('div.flash').length){
		$('div.flash').prependTo('#primary').find('.closer').hide();
	}
};

B.user.ajaxLocationSubmit = function(e){
	// TODO, should be able to just pass a validated form
	var $theForm = $(e.target),
		URL		 = "/json/asynclocation",
		inputText = $theForm.find('input[name=bl_user-zip_text]').length 
						? $theForm.find('input[name=bl_user-zip_text]').val() 
						: $theForm.find('.user-entry-input').val();
				
		$theForm.find('.user-entry-input').val(inputText);	
	    $theForm.find('input[name=bl_user-zip]').val(inputText);	
	//var headline = 
	//$theForm.append('<input type="hidden" name="ajax-headline" value="'+headline+'">');
	
	
	var data = $theForm.serialize(); 

	$.post(URL, data, function(ret){
		// var ret = {"data":[],"status":{"id":"ERROR","error":"invalid_location_number","bl_user-zip":"99999"}};
		if(ret.status){
			if(ret.status.id == "ERROR"){
				$theForm.find('label.error').remove().end()
					.find('fieldset').append('<label class="error" for="user-zip">'+_t[ret.status.error]+'</label>');
				
				if(ret.status.error == "invalid_location_number" || ret.status.error == "invalid_location_string"){
					$('label.error span', $theForm).text(inputText);
				}	
				
			}
			else if(ret.status.id == "SUCCESS"){
				if(ret.data['0'] ){
					var list = B.user.buildSetLocationList(ret);
                    var $locOver = $('#location-overlay');
					$locOver.find('.set-location-wrap').hide();
                    $locOver.find('.overlay-inner').append('<div class="select-location">'+ list +'</div>');
				    $locOver.find('.error').remove();	
					$locOver.css("height", "350px");
						//.find('a.close').css("right", "15px");
				} else if(ret.data.redirect){
					window.location = ret.data.redirect;
				}
			}
			
		}
		
	}, "json");
	
	return false;
};
B.user.buildSetLocationList = function(json){
	var list, data = json.data;
	var suggested = data[0].longname + '?';
	var bl_destination = json.bl_destination || "null";
	// console.log(bl_destination);
	
	list = '<h2>'+_t['did_you_mean']+' '+ suggested +'</h2>';
	list += '<div class="yellow-action-buttons">';
	list += '<a class="button"  href="'+B.settings.basePath+'confirm-location?bl_location='+data[0].longname+'&bl_destination='+data[0].bl_destination+'">'+_t['yes_use_this']+'</a>';
	list += '<a href="#" class="return-to-input" >'+_t['cancel']+'</a>'; //class="cancel-overlay"
	list += '</div>';
	list += '<div class="other-choices">';
	list += '<h3>'+_t['other_choices']+'</h3>';
	list += '<ul class="did-you-mean-list">';
	
	$(data).each(function(i){
		if(i===0)return; //the first one is our 'suggested' item above.
		if(data[i].longname){
			list += '<li><a href="'+B.settings.basePath+'confirm-location?bl_location='+data[i].longname+'&bl_destination='+data[i].bl_destination+'">'+data[i].longname+'</a></li>';
		} else{
			list += '<li><a href="'+B.settings.basePath+'confirm-location?bl_location='+data[i].name+'&bl_destination='+data[i].bl_destination+'">'+data[i].name+'</a></li>';
		}	
	});
	list += '</ul></div>';
    
    $('.return-to-input').live('click', function(){
        $('.select-location').remove();
        $('.overlay-inner .set-location-wrap').show();
    });

	return list;

};
B.user.locationLightBox = function(){
	
	$('.set-location-wrap form').append('<input type="hidden" name="bl_destination" id="bl_destination" value="'+window.location.pathname+'">');

	// ie hates the apple effect. a lot.
	var theEffect = $('html').is('.ieold, .ie8, .ie9') ? 'default' : 'apple'; 

	$('#location-overlay').overlay({
	
		mask: 'black',
		effect: theEffect,
	
		onBeforeLoad: function() {

			// grab wrapper element inside content
			var wrap = this.getOverlay().find(".overlay-inner");

			//reset it in case it was previously opened and abandoned
			wrap.html('');
			this.getOverlay().css('height', '200px');				
			
			var form = $('#stuff-for-js .set-location-wrap').clone(true);
			wrap.append(form);
			
		},
		onLoad: function(){
			$('#location-overlay input[type=text]')
				.focus();
				//.autocomplete(B.settings.autoCompleteUrl, B.settings.autoCompleteOptions);
			$('#location-overlay .form-set-location').submit(B.user.ajaxLocationSubmit);
		}
	
	});
	
	// make it available to other functions
	B.user.locationOverlay =  $("#location-overlay").data("overlay");
	
	// Load it on location change click
	$("a.loc-change").bind('click', function(){
		B.user.locationOverlayHeader = '<h2>'+_t['find_help']+'</h2>';
		$('#bl_destination').val(window.location.pathname);
		B.user.locationOverlay.load();
		return false;
	});	
	

	$('.cancel-overlay').live('click', function(){
		$(".overlay").find(".close").click();
	});
	
};
B.user.forceLocalize =  function(){
	var localized = B.user.isLocalizedCheck();
	if(!localized){
		$('.nav-find a, .nav-contributors a').bind('click', function(e){
			if($(this).parents('.nav-contributors').length){
				B.user.locationOverlayHeader = '<div class="flash">'+_t['set_location_contrib']+'</div><h2 class="hdr-set-location">'+_t['set_location']+'</h2>';
				$('#bl_destination').val(B.settings.basePath + 'leaderboard');
			}else{
				B.user.locationOverlayHeader = '<h2>'+_t['find_help']+'</h2>';
				$('#bl_destination').val(B.settings.basePath + 'find');
				
			}
			B.user.locationOverlay.load();
			return false;
		});
	}
	
};
B.tools.fixOldIEVersions = function(){
	if($('html').is('.ieold')){
		
		//fixes for no :before/:after properties
		$('.count, .location-hdr .zip-code').not('.null')
			.before('<span class="paren left-paren">(</span>')
			.after('<span class="paren right-paren">)</span>');
		
		$('.comment-body time').prepend('--');
		
	}
	if($('html').is('.ie6')){

	}
	
	
};
B.map.desktopMapStuff = function(){
	if(!jQuery.isEmptyObject(B.mapData)){
		B.map.init();
	}
	
	if($('li.local').is('.inactive')){
		$('#page-map').hide();
	}
	$('#page-map')
		.delegate('.smaller-map', 'click', B.map.viewSmallerMap)
		.delegate('.larger-map', 'click', B.map.viewLargerMap);
	
};
B.tools.desktopHelpIcons = function(){
	$('.help-screen').hide();
	$(".ui-icon.help").tooltip({ 
		position: "top center", 
		effect: "fade",
		delay: 400 ,
		onBeforeShow: function(){
			if($('html').is('.ie6')){
				$('select').css('visibility', 'hidden');
			}
		},
		onHide: function(){
			if($('html').is('.ie6')){
				$('select').css('visibility', 'visible');
			}
			
		}
	});
	$(".ui-icon.help").click(function(e){
		e.preventDefault();
		return false;
	});
};

B.user.autoCompleteLocations = function(){
	
	B.settings.autoCompleteUrl = B.settings.baseURL + '/api/getmatchingcities?isocountrycode=us';
	B.settings.autoCompleteOptions = {
		minChars:3,
		timeout:300,
		validSelection:false,
		//parameters:{'myparam':'myvalue'},
		before : function(input,text) {
			// make sure the right thing gets sent to the API in case some one hits enter/'Go' 
			// without selecting from the autocomplete list
			input.next('input').val(text);
		},
		onselect : function(input, text){

		},
		after : function(input,text) {
		}
	};	
	// autocomplete for the modal is set in the onload handler for the box (since it doesn't exist on page load)
	$('#user-zip, #user-zip-sidebar').autocomplete(B.settings.autoCompleteUrl, B.settings.autoCompleteOptions);
	
};




(function($) {
	
	B.bootstrap();
	B.tools.modalBoxSetup();
	B.tools.findAccordion();
	B.tools.tabButtonIcons();
	B.tools.repositionFlashMessages();
	B.user.locationLightBox();
	// B.user.leaderBoardAccordionInit();
	B.tools.userNav();
	B.map.desktopMapStuff();
	
	B.tools.desktopHelpIcons();
	
    //$().submit(B.locationSubmit);
	B.user.forceLocalize();
	B.tools.fixOldIEVersions();

	$('#keyword').labelifier();
	B.user.autoCompleteLocations();
	
})(jQuery); //ready



