var Services = {
  doYQLAjax: function(url){
    // if the URL starts with http
	// http://james.padolsey.com/javascript/cross-domain-requests-with-jquery/
	alert(url);
    if(url.match('^http')){
      // assemble the YQL call
//      msg.removeClass('error');
//      msg.html(' (loading...)');
      $.getJSON("http://query.yahooapis.com/v1/public/yql?"+
                "q=select%20*%20from%20html%20where%20url%3D%22"+
                encodeURIComponent(url)+ 
                "%22&format=xml&callback=?",
        function(data){
          if (data.results[0]) {
		  	var data = Services.filterData(data.results[0]);
				return data;
			}
			else {
				Utility.flash("Sorry, remote service out of order")
			};
        }
      );
    };
  },
  callIframe: function(url, callback, iFrame ) {
  	iFrame = 'iframe#' + iFrame;
    $( iFrame ).attr('src', url);
  },
  filterData: function(data){
    // filter all the nasties out
    // no body tags
    data = data.replace(/<?\/body[^>]*>/g,'');
    // no linebreaks
    data = data.replace(/[\r|\n]+/g,'');
    // no comments
    data = data.replace(/<--[\S\s]*?-->/g,'');
    // no noscript blocks
    data = data.replace(/<noscript[^>]*>[\S\s]*?<\/noscript>/g,'');
    // no script blocks
    data = data.replace(/<script[^>]*>[\S\s]*?<\/script>/g,'');
    // no self closing scripts
    data = data.replace(/<script.*\/>/,'');
    // [... add as needed ...]
    return data;
  }
}

var Amazon = {
	AMAZON_BASE: 'http://astore.amazon.co.uk',
	go: function( id ) {
    	$('#tripmain').html('<iframe id="amazon" name="amazon" width="760px" height="1000"></iframe>');
  		Services.callIframe( Amazon.AMAZON_BASE + "/tripscapecouk-21", Amazon.display, 'amazon' );
	}
}

var GeoPlugin = {
	gp_convertIt: function ( gp_from, gp_to, gp_amount, div_code ) { 
		$.getJSON( "http://www.geoplugin.net/currency_converter.gp?jsoncallback=?", 
			{ from:gp_from, to:gp_to, amount:gp_amount }, 
				function(output){ 
					GeoPlugin.displayCurrencyResult( output, div_code );
		}); 
	},
	displayCurrencyResult: function( output, div_code ){
		request_div = "#" + div_code + "_request";
		result_div = "#" + div_code + "_result";
		$( request_div ).html( output.from.symbol + " " + output.from.amount );
		$( result_div ).html( output.to.symbol + " " + output.to.amount );	
	}
}

var Google = {
	GOOGLE_BASE: 'http://www.google.com/',
	weather: function(name, lat, lng){
		var strLat = Google.formatLatLng( lat );
		var strLng = Google.formatLatLng( lng );
//		alert('weather');
//		alert(lat);
//		alert(lng);
//		alert(strLat);
//		alert(strLng);
		var name = name.replace(/ /g, "+");
		var uri = Google.GOOGLE_BASE + "/ig/api?weather=,,," + strLat + "," + strLng;
//		var uri = Google.GOOGLE_BASE + "/ig/api?weather=" + name;
		$.ajax({
			type: 'GET',
			url: '/utility/fetch_web',
			data: 'type=xml&uri=' + uri,
			success: function(result){
				Google.weatherDisplay(result);
			},
			error: function(){
				Utility.flash('Forecast unavailable');
			}
		});
	},
	formatLatLng: function( coordinate ){
//		alert(coordinate);
		var precision = ( coordinate >= 10 || coordinate <= -10 ) ? 6 : 7 ;
		var cString = Number( coordinate ).toFixed(precision).replace( /[\.]/, "" );
		return cString;
	},
	weatherDisplay: function(XMLresult){
		$('div#weather-today').html("");
		$('div#forecast-summary').html("");
		var forecast = $(XMLresult);
		var data_date = forecast.find('forecast_date').attr('data');
		if ( !data_date ){
			Utility.flash('Current weather not available');
			return;
		};
		var condition = forecast.find('current_conditions condition').attr('data');
		var icon = forecast.find('current_conditions icon').attr('data');
		var temp_c = forecast.find('current_conditions temp_c').attr('data');
		var humidity = forecast.find('current_conditions humidity').attr('data');
		var html = Google.buildToday(condition, icon, temp_c, humidity);
		$('div#weather-today').html(html);
		var forecast_days = forecast.find('forecast_conditions');
		html = "";
		$.each(forecast_days, function(){
			var day = $(this);
			var condition = day.find('condition').attr('data');
			var icon = day.find('icon').attr('data');
			var low =  Utility.makeCentrigrade( Number( day.find('low').attr('data')));
			var high = Utility.makeCentrigrade( Number( day.find('high').attr('data')));
			var day_of_week = day.find('day_of_week').attr('data');
			html += Google.buildForecastDay(day_of_week, condition, icon, high, low);			
		});
		$('div#forecast-summary').html(html);
	},
	buildToday: function(condition, icon, temp_c, humidity){
		var icon = Google.GOOGLE_BASE + icon;
		htm = "<ul class='forecast'>";
		htm += "<li>Latest " + temp_c + "&deg;C</li>";
		htm += "<li><img src='" + icon + "' alt='" + condition + "'>" 
		htm += "<li>" + condition.replace(/[ ]/,"<br \>") + "</li>";
		htm += "<li>" + humidity + "</li>";
		htm += "</ul>";
		return htm;
	},
	buildForecastDay: function(day_of_week, condition, icon, high, low){
		var icon = Google.GOOGLE_BASE + icon;
		htm = "<ul class='forecast left'>";
		htm += "<li><img src='" + icon + "' alt='" + condition + "'></li>" 
		htm += "<li>" + day_of_week + " " + high + "&deg;</li>";
		htm += "</ul>";
		return htm;
	}
}
//	,
//	xweather: function(location){
//		var location = location.replace(/[ ]/g, "+");
//		params = {
//			weather: location,
//			format: 'xm'
//		};
//		$.getJSON("http://www.google.com/ig/api?jsonp=?", params, function(json){
//			//				console.log( json );
//			//				var result = $.xmlDOM( json );
//			//				console.log( result );
//		});
//	}
//}
//http://www.google.com/ig/api?weather=keetmanshoop
//http://blog.programmableweb.com/2010/02/08/googles-secret-weather-api/

// http://www.programmableweb.com/api/world-weather-online

//var worldWeather = {
//	APIkey: 'b410a5e169134452102005';
//}
//var exchangeRate = {
//	APIkey: 'ZY7J4-p25Tx-5sQqJ';
//// http://www.exchangerate-api.com/from_curr/to_curr/amount?k=API_KEY
//}
