var home = true;
var search_id = '';

$(document).ready(function(){
	
	$('#searchbox, #searchbox_h').bind({
		focus: function(){
			if ($(this).val() == 'Enter your destination')
				$(this).val('');
			$(this).css('color','black');
		},
		blur: function(){ 
			if ($(this).val() == '')
				$(this).css('color','#DDD').val('Enter your destination');
		}
	});

	$('#btn_submit, #btn_submit_h').click(function(ev){
		ev.preventDefault()
		if (home) {
			home = false;
			$('#map').slideDown().removeClass('hide');
			$('#search_page').hide();
			$('#result_page').fadeIn();
			
			// moving auto suggest to header
			var suggestion = $('#suggestions').detach(); 
			suggestion.children().empty();
			$('#result_page_header').addClass('container', 'clearfix').removeClass('hide').append(suggestion);
			document.getElementById("suggestions").style.display="none";
			$('#suggestions').removeClass('autosuggest-large').addClass('autosuggest-small');
			
			$('#footer').removeClass('home_footer');
			search_id='searchbox';
		} 
		else {
			search_id='searchbox_h';
			clearContent();
		}

		var input = $('#'+search_id).val();
		if (input =='') { 
			$('#searchbox').focus();
		}
		else {
			var destination = input;
			$('#searchbox').val('');
			$('#suggestions').hide();
			//update result box header
			$('.destination').html(destination.split(',')[0]);
			checkWeather(destination);		
			retrievePhotos(destination);
			checkWiki(destination.split(',')[0])
			//get news				
			var newsURL = constructRequestURL(destination);
			retrieveLocalNews(newsURL)
			
			//load map
			initMap(destination);
			
			//get a list of place to eat
			getPlaceToEat(destination);
		}
	});
	
	//misc event checking
	var myMap = null;
	myMap = new VEMap('map_container');
	myMap.LoadMap();
	$(window).resize(function() {
		var w = $(window).width(); 
		myMap.Resize(w,322);
	});
	// remove the last bottom border for food block
	//$('#food .restaurant_block:last').removeClass('restaurant_block');
});

checkWeather = function(dest) {
	var requestURL = 'http://www.worldweatheronline.com/feed/weather.ashx?'+'q='+ dest +'&format=json&num_of_days=5&key=479563ba02211730112401&callback=?';
	$.getJSON(requestURL, function(data){
		$.each(data, function(i,item){
			var current_condition = item.current_condition;
			var five_days_forecast = item.weather;
			extractCurrentCondition(current_condition);
			extract5DaysForecast(five_days_forecast);
		})
	}); // end of getJSON
}

extractCurrentCondition = function(cur_condition) {
	$.each(cur_condition, function(i,data){
		var weatherDescriptionClass = data.weatherDesc[0].value.capitalize().replace(/\s*/g,'');
		var html = '<div id="main" class="overflow">';
		html += '<p id="temperature" class="weather_icon '+weatherDescriptionClass+'">' + data.temp_F + '<span><em>o</em>F</span></p>';
		var weather_description = data.weatherDesc;
		$.each(weather_description, function (i,e){
			html += '<p id="condition" class="align_center">'+ e.value + '</p>'; 
		});			
		html+= '</div>';
		
		html+= '<div id="sub">'
		html+= '<p class="align_center">Humidity:' + data.humidity + '% - Visibility:'+ data.visibility +'</p>';
		html+= '</div>';

		$('#current_weather').append(html);
	})
}

extract5DaysForecast = function(forecast){
	var weekdays = ['Sun','Mon','Tue','Wed','Thu','Fri','Sat'];
	var d = new Date();
	var today = d.getDay(); 
	$.each(forecast,function(i,item){ /* console.log(item.weatherDesc[0].value) */
		if((i > 0) && (i < 4)) {
			var html = '<div class="day_block">';
			var nextday = today + i;
			if (nextday>=7) 
				nextday -=7;
			html += '<h4>' + weekdays[nextday] + '</h4>';
			
			var weatherDescriptionClass = '';
			var weather_description = item.weatherDesc;
			$.each(weather_description, function (i,e){
				weatherDescriptionClass = e.value.capitalize().replace(/\s*/g,'');
			});
			
			var weatherIconUrl = item.weatherIconUrl;
			$.each(weatherIconUrl, function(i, e){
				html += '<div class="fl_left icon '+weatherDescriptionClass+'">'/* + '<img src="'+e.value+'"/>' */ + '</div>';
			});
			html += '<div class="fl_left"><p>' + item.tempMaxF + '</p>';			
			html += '<p>' + item.tempMinF + '</p></div>';
			
			html += '</div>';
			$('#forecast').append(html);		
		}				
	})
}

retrievePhotos = function(dest) {
	var apiKey = '4ef2fe2affcdd6e13218f5ddd0e2500d';
	var requestUrl = 'http://api.flickr.com/services/rest/?&method=flickr.photos.search&api_key=' + apiKey +'&geo_content=2&accuracy=6&text='+dest+'&sort=relevance&tag_mode=all&tags='+dest+'&per_page=60&format=json&jsoncallback=?';
	$.getJSON(requestUrl,
		function(data){
			$.each(data.photos.photo, function(i,item){
				//console.log(i,'=',item);
				var thumbURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '_s.jpg';
				var photoURL = 'http://farm' + item.farm + '.static.flickr.com/' + item.server + '/' + item.id + '_' + item.secret + '.jpg';
				var thumb = $('<img/>').attr({ 
						src: thumbURL,
						id: i
					}).click(function(){
						var imgPreload = new Image();
						imgPreload.src = photoURL;
						var photoCaption = item.title;
						var insertPos = 0;
						var clickedItem = $(this).attr('id');
						var clickedRow = Math.floor(clickedItem/7);
						if ($('#large_photo_wrapper').length > 0) {
							$('#large_photo_wrapper').remove();
						}
						var largeImgBlock = '<div id="large_photo_wrapper" class="relative hide"><div id="btn_close" class="absolute pointer"></div><img src="'+photoURL+'"><p id="title"><em>'+photoCaption+'</em></p></div>';
						if (clickedRow == 8) {
							insertPos = $('#photos_wrapper > img').length-1;
						} else {
							insertPos = (Math.floor(clickedItem/7)+1)*7 - 1;
						}
						($(this).parent().find('#'+insertPos)).after(largeImgBlock);
						$('#large_photo_wrapper').slideDown('fast');
						$('#btn_close').click(function(){
							$(this).parent().slideUp('fast');
							_gaq.push(['_trackEvent', 'Images_gallery', 'close', 'Somebody closes popup image']);
						})
				});
				$('#photos_wrapper').append(thumb);
			});
	}); // end of JSON test
}	

getPhotoCredit = function(userId) {
	var apiKey = '50ad28ecafb8c1022d409d3519a75c90';
	var requestUrl = 'http://api.flickr.com/services/rest/?&method=flickr.people.getInfo&api_key='+ apiKey +'&user_id='+ userId + '&format=json&jsoncallback=?';
	return $.getJSON(requestUrl,
		function(ownerData){
			//console.log('return data from get credit:',ownerData);
			photoCredit = ownerData.person.realname._content;
		})
}

// create request query
constructRequestURL = function(dest) {
	AppId = "F5EB2131EA29E51EE3AC0FC67E7AD3945351710E";
	var URL = "http://api.bing.net/" +
		"json.aspx?"+
		"AppId=" + AppId + 
		"&Query=" + dest +
		"&Sources=News" +
		"&Version=2.0" +
		"&News.SortBy=Relevance" +
		"&News.Offset=0" +
		"&JsonType=callback" + 
		"&JsonCallback=?";
	return encodeURI(URL);
}

retrieveLocalNews = function(requestURL) {
	$.getJSON(requestURL,
		function(data){
			newResults = data.SearchResponse.News.Results;
			$.each(newResults, function(i,news){
				var html = '';
				if (i==9)
					html = '<div>'
				else
					html = '<div class="news_block">';
				html += '<h3>' + '<a href='+ news.Url +'>'+ news.Title + '</a></h3>';
				html += '<p><strong>Date:</strong>';					
				html += news.Date + '</p>';
				html += '<p>' + news.Snippet + '</p>';
				html += '<p><strong>Source: </strong>';
				html += '<a href='+ news.Url +'>' + news.Source + '</a></p>';
				//html += news.Url + '</p>';
				html += '</div>';
				$('#news_wrapper').append(html);
			})
		}
)}

initMap = function(location) {
	var myMap = null;
	myMap = new VEMap('map_container');
	myMap.LoadMap();
	var zoomLevel = 12; 
	var resultIndex = 1;
	var numberOfResult = 10;
	var showResults = false;

	var pinsLayer = new VEShapeLayer();
		pinsLayer.SetTitle('attractionLayer');
		myMap.AddShapeLayer(pinsLayer)

	var w = $(window).width(); 
	myMap.Resize(w,322);
	myMap.Geocode(location);
	myMap.Find('attractions',location, null, pinsLayer,resultIndex, numberOfResult, showResults, true, true, true, function(data){
		myMap.SetZoomLevel(zoomLevel);
		$.each(data.Annotations, function(i,item){
		
		// create custom pins and push them on the map
		var pin = new VEShape(VEShapeType.Pushpin, new VELatLong(item.Latitude, item.Longitude));
		var pinTitle = item.DisplayOrder + ':' + item.Title;
			pin.SetTitle(pinTitle);
			pin.SetDescription(item.Notes);
		var spec = new VECustomIconSpecification();		
		spec.Image = 'images/pin.png'
		pin.SetCustomIcon(spec);
		myMap.AddShape(pin);
		
		var attraction_id = item.DisplayOrder + 1;
		//create legend
		html = '<div class="attractions_legend clearfix">';
		html += '<p class="attraction_id" >' + attraction_id + '</p>' ;
		html += '<p><strong>' + item.Title + '</strong></p>';
		html += '<p><strong>Address: </strong>' +item.Notes + '</p>';
		html += '</div>';
		if (item.DisplayOrder %2 == 0)
			$('#legend-l').append(html);
		else
			$('#legend-r').append(html);
		});
	});
} 		
// Yelp API hasn't worked with latest jQuery yet
getPlaceToEat = function(location){
	var auth = { 
		consumerKey: "pn2XI8aen9od_RF7hPo4EA", 
		consumerSecret: "shkHHxAZHveGrg_iHV5TMvNzR5c",
		accessToken: "wLWh0AHBWgFVDGFtbIp5YQ-cYvTWQc66",
		accessTokenSecret: "MC3pzpZ48qv8-khjsyDPhIw8qNI",
		serviceProvider: { 
		signatureMethod: "HMAC-SHA1"
		}
	};

	var terms = 'food';
	var near = location;

	var accessor = {
		consumerSecret: auth.consumerSecret,
		tokenSecret: auth.accessTokenSecret
	};

	parameters = [];
	parameters.push(['term', terms]);
	parameters.push(['location', near]);
	parameters.push(['callback', 'cb']);
	parameters.push(['oauth_consumer_key', auth.consumerKey]);
	parameters.push(['oauth_consumer_secret', auth.consumerSecret]);
	parameters.push(['oauth_token', auth.accessToken]);
	parameters.push(['oauth_signature_method', 'HMAC-SHA1']);

	var message = { 
		'action': 'http://api.yelp.com/v2/search',
		'method': 'GET',
		'parameters': parameters 
	};

	OAuth.setTimestampAndNonce(message);
	OAuth.SignatureMethod.sign(message, accessor);

	var parameterMap = OAuth.getParameterMap(message.parameters);
	//console.log(parameterMap);

	$.ajax({
		'url': message.action,
		'cache' : true,
		'data': parameterMap,
		'dataType': 'jsonp',
		'jsonpCallback': 'cb',
		'success': function(data, textStats, XMLHttpRequest) {
			//console.log(data.businesses);
			$.each(data.businesses, function(i,item){
				extractRestaurantInfo(item);
			});
		}
	});
}

extractRestaurantInfo = function(restaurant){
	// condition to display restaurants with rating > n
	var rating_condition = 3
	var rate = [];
	rate = restaurant.rating_img_url.split('/');
	star = rate[rate.length-1];
	rate = star.split('.')
	star = rate[0].split('_')
	if (star[1] > rating_condition){
		//console.log(restaurant);
		var html = '<div class="restaurant_block clearfix">';
		html += '<img class="restaurant_thumb fx_shadow" src="'+restaurant.image_url+ '"/>';
		html += '<div class="span-11"><h3>' + restaurant.name + '</h3>';
		html += '<p>Category:' + restaurant.categories[0]+'</p>';
		html += '<p>Rating:' + '<span class="rating-img"><img src="'+restaurant.rating_img_url + '"/></span><span>('+ restaurant.review_count +'reviews)</span>' +'</p>';					
		html += '<p>Address: '+ restaurant.location.display_address + '</p>';
		if (restaurant.display_phone != undefined ) {
			html += '<p>Tel.: ' + restaurant.display_phone + '</p>';		
		}
		html += '<p>Review: ' + '<a href="'+ restaurant.url + '">' + restaurant.url + '</a></p>';
		html += '</div></div>';
	}
	$('#food').append(html);
}

//clear all content for result page layout
clearContent = function(){
	$('#legend-l,#legend-r,#photos_wrapper,#food,#news_wrapper').html('');
	$('#current_weather').html('<h3>Current Condition</h3>');
	$('#forecast').html('<h3>Next Days Forecast</h3>');
}

//auto suggest
suggest = function(inputString){
	if(inputString.length == 0) {
		$('#suggestions').fadeOut();
	} else {
		$.post("action/autosuggest.php", {queryString: ""+inputString+""}, function(data){
			if(data.length > 0) {
				$('#suggestions').fadeIn();
				$('#suggestionsList').html(data);
			}
		});
	}
}

// fill input with result coming back from auto suggest
fill = function(thisValue) {
	if (home) {
		input_id='searchbox';
	}else {
		input_id='searchbox_h';
	}
	$('#'+input_id).val(thisValue);
	setTimeout("$('#suggestions').fadeOut();", 500);
}

// capitalize string using reg exp
String.prototype.capitalize = function(){
	return this.replace( /(^|\s)([a-z])/g , function(m,p1,p2){return p1+p2.toUpperCase();});
};

// grab Wiki content based on use input and content availability of wiki source
grabWiki = function(url) {
	$.post("action/grabwiki.php", {queryString: ""+url+""}, function(data){
		if(data.length>0) {
			$('#wiki_wrapper').html(data);
		}
	});
}

//check to see if destination article is available on wikipedia.
checkWiki = function(dest) {
	if (!dest)
		return;
	requestURL = 'http://en.wikipedia.org/w/api.php?action=opensearch&search='+dest+'&format=json&callback=?';
	$.getJSON(requestURL, function(data){
		var found = false;
		var url='';
		var articleName = data[0];
		if (articleName != dest) 
			return;
		for (i=0; i<data[1].length; i++) {
			if (articleName.toLowerCase() == data[1][i].toLowerCase()) {
				found = true;
				articleName = articleName.replace(/\s/g,'_');
				url ='en.wikipedia.org/wiki/'+articleName;
				grabWiki(url);
			}
		}
		if (!found) {
			if (data[1][0].indexOf(',') != -1) {
				var str = data[1][0].split(',');
				if (articleName.toLowerCase() == str[0].toLowerCase()) {
					found = true;
					articleName = data[1][0].replace(/\s/g,'_');
					url ='en.wikipedia.org/wiki/'+articleName;
					grabWiki(url);
				}
			}
		}else {
			//$('#wiki_container').hide();
		}
	});
};

/* 	wishlist:
		5. exchange rate, with local currency first
		6. other activities
		3. Replace Yelp API with Google Place API.
		7. wiki: a. expandable. b.redirect to correct wiki page if there are many sources. 
		1. ajax loading indicator.
		2. add translation
		9. attractions linked to stars on map.
		1. sanitize input for auto suggest. set ajax cache: true.
*/

