/*---------------
Hydro Calculation
---------------*/
//var language = window.navigator.userLanguage || window.navigator.language;
//alert(language);
// Storing Factor Values

var hydroCalculator = {
	// Exercise Values
	exerciseMode: {
		aerobics:0.7,
		american_football: 0.6,
		baseball: 0.8,
		basketball: 0.74,
		cycling: 0.7,
		football: 0.85,
		golf: 0.46,
		hockey: 0.63,
		rugby: 0.8,
		running: 1.0,
		swimming: 0.6,
		tennis: 1.0,
		walking :0.50
	},
	// Intensity Values
	intensitySelect: {
		light: 0.6,
		moderate: 0.9,
		heavy: 1.2
	},
	// Temperature Values
	temperature: {
		temp_less_15: 0.16,
		temp_15: 0.32,
		temp_20: 0.81,
		temp_23: 1.0,
		temp_30:1.37,
		temp_35: 1.93,
		temp_greater_40: 2.25
	},
	// Weight Values
	weight: {
		 weight_40: 0.59,
		 weight_41: 0.59,
		 weight_42: 0.62,
		 weight_43: 0.62,
		 weight_44: 0.65,
		 weight_45: 0.65,
		 weight_46: 0.68,
		 weight_47: 0.68,
		 weight_48: 0.71,
		 weight_49: 0.71,
		 weight_50: 0.74,
		 weight_51: 0.74,
		 weight_52: 0.77,
		 weight_53: 0.77,
		 weight_54: 0.80,
		 weight_55: 0.80,
		 weight_56: 0.83,
		 weight_57: 0.83,
		 weight_58: 0.86,
		 weight_59: 0.86,
		 weight_60: 0.89,
		 weight_61: 0.89,
		 weight_62: 0.92,
		 weight_63: 0.92,
		 weight_64: 0.94,
		 weight_65: 0.94,
		 weight_66: 0.96,
		 weight_67: 0.96,
		 weight_68: 0.98,
		 weight_69: 0.98,
		 weight_70: 1.00,
		 weight_71: 1.00,
		 weight_72: 1.02,
		 weight_73: 1.02,
		 weight_74: 1.04,
		 weight_75: 1.04,
		 weight_76: 1.055,
		 weight_77: 1.055,
		 weight_78: 1.07,
		 weight_79: 1.07,
		 weight_80: 1.085,
		 weight_81: 1.085,
		 weight_82: 1.10,
		 weight_83: 1.10,
		 weight_84: 1.115,
		 weight_85: 1.115,
		 weight_86: 1.13,
		 weight_87: 1.13,
		 weight_88: 1.14,
		 weight_89: 1.14,
		 weight_90: 1.155,
		 weight_91: 1.155,
		 weight_92: 1.165,
		 weight_93: 1.165,
		 weight_94: 1.18,
		 weight_95: 1.18,
		 weight_96: 1.19,
		 weight_97: 1.19,
		 weight_98: 1.215,
		 weight_99: 1.215,
		 weight_100: 1.23,
		 weight_101: 1.23,
		 weight_102: 1.245,
		 weight_103: 1.245,
		 weight_104: 1.27,
		 weight_105: 1.27,
		 weight_106: 1.285,
		 weight_107: 1.285,
		 weight_108: 1.30,
		 weight_109: 1.30,
		 weight_110: 1.315
	},
	finalResult: 0,
	selectedCountry : "New York",
	selectedSport : "Football",
	selectedIntensity : "Light",
	selectedweightkg: 0,
	selectedweightlb: 0,
	selectedheightcm: 0,
	selectedheightinch: 0,
	selecteddurationmin: 0,
	selecteddurationhour: 0,
	mylat : 0,
	mylong : 0
}

/*--------
Selection 
---------*/

// Select Country
$('#country-select .location-done').live('click', function(){
	if($('#searchbox').val() == ""){
	
	}
	else{
		hydroCalculator.selectedCountry =$('#searchbox').val();
	}
});


// Select Sport
$('#sports-select .share-list a.ui-link-inherit').live('click', function(){
	hydroCalculator.selectedSport = $(this).text();
	//console.log(hydroCalculator.selectedSport);
});


// Select Intensity
$('#intensity-select .share-list a.ui-link-inherit').live('click', function(){
	hydroCalculator.selectedIntensity = $(this).text();
	//console.log(hydroCalculator.selectedIntensity);
});


$('#settings-page').live('pageshow', function(e) {
	$('#settings-page ul:eq(0) li:eq(0) a.select-one').text(hydroCalculator.selectedCountry);
});


/*----------------------- 
Radio button change event
------------------------*/

// Time Slider Toggle
$("#hyd-calc .duration-slider input[type='radio']").live( "change", function(event, ui) {
  $('.time-slider').toggle();
});

// Weight Slider Toggle
$("#hyd-calc .weight-slider input[type='radio']").live( "change", function(event, ui) {
  $('.kglb-slider').toggle();
});

// Weight Slider Toggle
$("#hyd-calc .height-slider input[type='radio']").live( "change", function(event, ui) {
  $('.ht-slider').toggle();
});

// Temperature Slider Toggle
$("#hyd-calc .temp-slider input[type='radio']").live( "change", function(event, ui) {
  $('.temptype-slider').toggle();
});

$('#hyd-calc a').live('click', function(){
	if( $('.kg-slider').is(':visible') ) {
		id_number = 1;
	}
	else {
		id_number = 0;
	}
	if( $('.cm-slider').is(':visible') ) {
		id_number1 = 1;
	}
	else {
		id_number1 = 0;
	}
	if( $('.min-slider').is(':visible') ) {
		id_number2 = 1;
	}
	else {
		id_number2 = 0;
	}
	if( $('.faren-slider').is(':visible') ) {
		id_number3 = 1;
	}
	else {
		id_number3 = 0;
	}
	localStorage.setItem('todo', id_number);
	localStorage.setItem('todo1', id_number1);
	localStorage.setItem('todo2', id_number2);
	localStorage.setItem('todo3', id_number3);
	//console.log(id_number3);
});

/*---------------
Final Calculation 
----------------*/

$('#hyd-calc a.calculate-button').live('click', function(){
	
	selectedSport = $("#hyd-calc .sport-select .ui-link-inherit").text();
	selectedIntensity = $("#hyd-calc .intensity-select .ui-link-inherit").text();
	
// Getting Exercise Final Result
	var exercise = selectedSport.toLowerCase().split(' ').join('_');
	var exerciseFinal = (hydroCalculator.exerciseMode[exercise]);
	
// Getting Intensity Final Result
	var intensity = selectedIntensity.toLowerCase();
	var intensityFinal = (hydroCalculator.intensitySelect[intensity]);
	
// Calculating for Weight, Time, Temperature
	var calculation = {
		// Weight
		kg: function (){
			return $('.kglb-slider #slider-2').val();
		},
		lb: function(){
			return Math.round($('.kglb-slider #slider-3').val() *  0.45359237);
		},
		
		// Time
		min: function (){
			return $('.time-slider #slider-5').val() / 60 ;
		},
		hours: function(){
			return $('.time-slider #slider-6').val() ;
		},
		
		// Temperature
		cel: function(){
			return $('.temptype-slider #slider-7').val();
		},
		far: function(){
			var farenheit = $('.temptype-slider #slider-8').val();
			var calFar = 5/9 * (farenheit-32);
			return calFar;
		}
	}
	
// Getting Weight Final Result
	var selectedweightUnit = $("input[name='radio-view-1']:checked").val();
	var selectWeight = calculation[selectedweightUnit]();
	
	if (selectWeight <= 40 ){
		var finalWeight = (hydroCalculator.weight.weight_40);
	}
	else if (selectWeight >= 110 ){
		var finalWeight = (hydroCalculator.weight.weight_110);
	}
	else {
	    var selectWeight = "weight_" + calculation[selectedweightUnit]();	
        var finalWeight = (hydroCalculator.weight[selectWeight]);
	}
	
// Getting Time Final Result
	var selectedTimeUnit = $("input[name='radio-view-3']:checked").val();
	var finalTime = calculation[selectedTimeUnit]();
	
// Getting Temperature Final Result
	var selectedTempUnit = $("input[name='radio-view-4']:checked").val();
	var calTemp = calculation[selectedTempUnit]();
	
	function calcTemperature() {
		if (calTemp < 15) {
			calcTemp = hydroCalculator.temperature.temp_less_15;
		} else if (calTemp >= 15 && calTemp < 20) {
			calcTemp = hydroCalculator.temperature.temp_15;
		} else if (calTemp >= 20 && calTemp < 23) {
			calcTemp = hydroCalculator.temperature.temp_20;
		} else if (calTemp >= 23 && calTemp < 30) {
			calcTemp = hydroCalculator.temperature.temp_23;
		} else if (calTemp >= 30 && calTemp < 35) {
			calcTemp = hydroCalculator.temperature.temp_30;
		} else if (calTemp >= 35 && calTemp < 40) {
			calcTemp = hydroCalculator.temperature.temp_35;
		} else if (calTemp >= 40) {
			calcTemp = hydroCalculator.temperature.temp_greater_40;
		}
		return calcTemp;
	}

	var tempFinal = calcTemperature();
	
// Getting Final Calculated Result
	var result = (exerciseFinal * intensityFinal * tempFinal * finalWeight * finalTime);
	hydroCalculator.finalResult = result.toFixed(3);
	
});


//Printing the Final Calculated Result in Result Page
	$('#result-page').live('pageshow', function(e) {
		$('#result-page .result-container .hydroLitres').text(hydroCalculator.finalResult + "lt");
		$('#result-page .result-container .hydroMl').text(hydroCalculator.finalResult*1000 + "ml");
	});


//Social network Sharing
	$('#socialshare-page').live('pageshow', function(e) {
		
		var randombg = Math.floor(Math.random()*3); // 0 to 2
		//alert(randombg);
		
		
		var fburl_1 = escape("https://www.facebook.com/dialog/feed?app_id=107388386030916&link=http://www.powerade.com.au/Utilities/HydrationCalculator.html&picture=http://f.cl.ly/items/0v0a0m2a0G2D1a0e200g/Screen%20shot%202011-10-14%20at%2012.06.48%20PM.png&name=Replenish!&description=Rehydrate for maximum results.&caption=I need ") +hydroCalculator.finalResult*1000+ escape(" ml of POWERADE to rehydrate after my workout!&message=Powerade!&redirect_uri=http://www.powerade.com");
		var fburl_2 = escape("https://www.facebook.com/dialog/feed?app_id=107388386030916&link=http://www.powerade.com.au/Utilities/HydrationCalculator.html&picture=http://f.cl.ly/items/0v0a0m2a0G2D1a0e200g/Screen%20shot%202011-10-14%20at%2012.06.48%20PM.png&name=Breaking A Sweat!&description=How intense was your workout today?&caption=I need ") +hydroCalculator.finalResult*1000+ escape(" ml of POWERADE to rehydrate after my workout!&message=Powerade!&redirect_uri=http://www.powerade.com");
		var fburl_3 = escape("https://www.facebook.com/dialog/feed?app_id=107388386030916&link=http://www.powerade.com.au/Utilities/HydrationCalculator.html&picture=http://f.cl.ly/items/0v0a0m2a0G2D1a0e200g/Screen%20shot%202011-10-14%20at%2012.06.48%20PM.png&name=Working Up A Thirst!&description=Know what your thirst is worth?&caption=I need ") +hydroCalculator.finalResult*1000+ escape(" ml of POWERADE to rehydrate after my workout!&message=Powerade!&redirect_uri=http://www.powerade.com");
		
		var twurl_1 = "http://twitter.com/home?status=Replenish! I've consumed " + hydroCalculator.finalResult*1000 + "ml of POWERADE during my workout!!! Rehydrate for maximum results. " ;
		var twurl_2 = "http://twitter.com/home?status=Breaking A Sweat! I've consumed " + hydroCalculator.finalResult*1000 + "ml of POWERADE during my workout!!! How intense was your workout today?" ;
		var twurl_3 = "http://twitter.com/home?status=Working Up A Thirst! I've consumed " + hydroCalculator.finalResult*1000 + "ml of POWERADE during my workout!!! Know what your thirst is worth?" ;
		
		
		if(randombg == 0) {
			var fbshare = unescape(fburl_1);
			$(".fbShare").attr('href', fbshare);
			
			$(".twshare").attr('href', twurl_1);
		}
		
		if(randombg == 1) {
			var fbshare = unescape(fburl_2);
			$(".fbShare").attr('href', fbshare);
			
			$(".twshare").attr('href', twurl_2);
		}
		
		if(randombg == 2) {
			var fbshare = unescape(fburl_3);
			$(".fbShare").attr('href', fbshare);
			
			$(".twshare").attr('href', twurl_3);
		}
	});


//Scripts to overide some of the default functionalities of jquerymobile 

$('#hyd-calc').live('pageshow', function(e) {
	$('.ui-dialog a .ui-btn-text').text('Cancel');
	$(".sport-select .ui-btn-text").append( "<span class='right-icon'><img src='styles/i/arrow-right-3g.png'></span>" );
	$(".intensity-select .ui-btn-text").append( "<span class='right-icon'><img src='styles/i/arrow-right-3g.png'></span>" );

	$("#slider-7").val(temp_cel).slider("refresh");
	$("#slider-8").val(temp_far).slider("refresh");
	
	$('input').keypress(function(e) {
	    var a = [];
	    var k = e.which;

	    for (i = 48; i < 58; i++)
	        a.push(i);

	    if (!(a.indexOf(k)>=0))
	        e.preventDefault();
	});
	
	$(".ui-slider-input").focusout(function() {
	    if($(this).val() == "") {
	        //alert("emptystring");
	        $(this).val(0); 
	    }
	});
	
	updatedNo = localStorage.getItem('todo');
	updatedNo1 = localStorage.getItem('todo1');
	updatedNo2 = localStorage.getItem('todo2');
	updatedNo3 = localStorage.getItem('todo3');
	//console.log(updatedNo3);
	
	if(updatedNo == 0) {
		$('.lb-slider').css('display','block');
		$('#radio-view-b').attr('checked','checked');
		$('#lb-radio').addClass('ui-btn-active');
		$('.kg-slider').css('display','none');
		$('#kg-radio').removeClass('ui-btn-active');
	}
	else {
		$('.lb-slider').css('display','none');
		$('.kg-slider').css('display','block');
	}
	
	if(updatedNo1 == 0) {
		$('.inch-slider').css('display','block');
		$('#radio-view-d').attr('checked','checked');
		$('#inch-radio').addClass('ui-btn-active');
		$('.cm-slider').css('display','none');
		$('#cm-radio').removeClass('ui-btn-active');
	}
	else {
		$('.inch-slider').css('display','none');
		$('.cm-slider').css('display','block');
	}
	
	if(updatedNo2 == 0) {
		$('.hours-slider').css('display','block');
		$('#radio-view-f').attr('checked','checked');
		$('#hours-radio').addClass('ui-btn-active');
		$('.min-slider').css('display','none');
		$('#min-radio').removeClass('ui-btn-active');
	}
	else {
		$('.hours-slider').css('display','none');
		$('.min-slider').css('display','block');
	}
	
	if(updatedNo3 == 0) {
		$('.celcius-slider').css('display','block');
		$('#radio-view-h').attr('checked','checked');
		$('#far-radio').addClass('ui-btn-active');
		$('.faren-slider').css('display','none');
		$('#cel-radio').removeClass('ui-btn-active');
	}
	else {
		$('.celcius-slider').css('display','none');
		$('.faren-slider').css('display','block');
	}
	
	
	$('#hyd-calc .kg-slider input[type="number"]').val(hydroCalculator.selectedweightkg).slider("refresh");
	$('#hyd-calc .lb-slider input[type="number"]').val(hydroCalculator.selectedweightlb).slider("refresh");
	$('#hyd-calc .cm-slider input[type="number"]').val(hydroCalculator.selectedheightcm).slider("refresh");
	$('#hyd-calc .inch-slider input[type="number"]').val(hydroCalculator.selectedheightinch).slider("refresh");
	$('#hyd-calc .min-slider input[type="number"]').val(hydroCalculator.selecteddurationmin).slider("refresh");
	$('#hyd-calc .hours-slider input[type="number"]').val(hydroCalculator.selecteddurationhour).slider("refresh");
	
	if((hydroCalculator.selectedweightkg!=0 || hydroCalculator.selectedweightlb!=0) && (hydroCalculator.selectedheightcm!=0 || hydroCalculator.selectedheightinch!=0) && (hydroCalculator.selecteddurationmin != 0 || hydroCalculator.selecteddurationhour != 0)) { 
 		$(".button-overlay").css("display","none");
 	}
	else {
		$(".button-overlay").css("display","block");
	}
	
	$('#hyd-calc .ui-input-text').bind('change',function() {
		var weightvalue1 = $('.kg-slider input[type="number"]').val();
		hydroCalculator.selectedweightkg = weightvalue1;    
		var weightvalue2 = $('.lb-slider input[type="number"]').val();
		hydroCalculator.selectedweightlb = weightvalue2;
		var heightvalue1 = $('.cm-slider input[type="number"]').val();
		hydroCalculator.selectedheightcm = heightvalue1;
		var heightvalue2 = $('.inch-slider input[type="number"]').val();
		hydroCalculator.selectedheightinch = heightvalue2;
		var durationvalue1 = $('.min-slider input[type="number"]').val();
		hydroCalculator.selecteddurationmin = durationvalue1;
		var durationvalue2 = $('.hours-slider input[type="number"]').val();
		hydroCalculator.selecteddurationhour = durationvalue2;
		//console.log(weightvalue1, weightvalue2, heightvalue1, heightvalue2, durationvalue1, durationvalue2);
	 	if((weightvalue1!=0 || weightvalue2!=0) && (heightvalue1!=0 || heightvalue2!=0) && (durationvalue1 != 0 || durationvalue2 != 0)) { 
	 		$(".button-overlay").css("display","none");
	 	}
		else {
			$(".button-overlay").css("display","block");
		}
	});
	
	$('#hyd-calc .sport-select a.select-one').text(hydroCalculator.selectedSport);
	$('#hyd-calc .intensity-select a.select-one').text(hydroCalculator.selectedIntensity);
	//console.log(hydroCalculator.selectedSport)

});



$('#socialshare-page').live('pageshow', function(e) {
	$(".share-list .ui-btn-text").append( "<span class='share-right-icon'><img src='styles/i/arrow-right-3g.png'></span>" );
});

$('#settings-page').live('pageshow', function(e) {
	$(".settings-select .ui-btn-text").append( "<span class='share-right-icon'><img src='styles/i/arrow-right-3g.png'></span>" );
	$(".country-select .ui-btn-text").append( "<span class='share-right-icon'><img src='styles/i/arrow-right-3g.png'></span>" );
});

$('#country-select').live('pageshow', function(e) {
	document.getElementById("searchbox").focus();
	var mapOptions = {
	   zoom: 10,
	   mapTypeId: google.maps.MapTypeId.ROADMAP,
	   center: new google.maps.LatLng(41.06000,28.98700)
	 };

	var map = new google.maps.Map(document.getElementById("map"),mapOptions);

	var geocoder = new google.maps.Geocoder();  

	 $(function() {
	  
	     $("#searchbox").autocomplete({
  
       source: function(request, response) {

	      if (geocoder == null){
	       geocoder = new google.maps.Geocoder();
	      }
	         geocoder.geocode( {'address': request.term }, function(results, status) {
	           if (status == google.maps.GeocoderStatus.OK) {

	              var searchLoc = results[0].geometry.location;
	           var lat = results[0].geometry.location.lat();
	              var lng = results[0].geometry.location.lng();
	              var latlng = new google.maps.LatLng(lat, lng);
	              var bounds = results[0].geometry.bounds;

	              geocoder.geocode({'latLng': latlng}, function(results1, status1) {
	                  if (status1 == google.maps.GeocoderStatus.OK) {
	                    if (results1[1]) {
	                     response($.map(results1, function(loc) {
	                    return {
	                        label  : loc.formatted_address,
	                        value  : loc.formatted_address,
	                        bounds   : loc.geometry.bounds
	                      }
	                    }));
	                    }
	                  }
	                });
	        }
	          });
	       },
	       select: function(event,ui){
	  var pos = ui.item.position;
	  var lct = ui.item.locType;
	  var bounds = ui.item.bounds;

	  if (bounds){
	   map.fitBounds(bounds);
	  }
	       }
	     });
	 });
});


//Scripts for getting the geo-location

temp_c = 0;
temp_f = 0;
temp_cel = 0;
temp_far = 0;

var Temp = {
  apiGetToken: function(resturl) {
    var url = resturl;
    Proxy.a({
      url: url, 
      type: 'get',
      data: {},
      dataType: 'text',
      success: function(res, status, XMLHttpRequest) {
			var obj = $.xml2json(res);
			var temp_c = obj.current_condition.temp_C;
			temp_cel = temp_c;
			//console.log(temp_cel);
			var temp_f = obj.current_condition.temp_F;
			temp_far = temp_f;
			//console.log(temp_far);
      }
    });
  }
};

var Myloc = {
  apiGetToken: function(mylocation) {
    var url = mylocation;
    Proxy.a({
      url: url, 
      type: 'get',
      data: {},
      dataType: 'text',
      success: function(res, status, XMLHttpRequest) {
			var obj = $.xml2json(res);
			var current_loc = obj.Result.city;
			hydroCalculator.selectedCountry = current_loc;
			//console.log(hydroCalculator.selectedCountry);
      }
    });
  }
};

$('#home-page, #hyd-calc').live('pageinit', function(){
	if (geo_position_js.init()) {
	  geo_position_js.getCurrentPosition(geo_success, geo_error);
	}
	
	function geo_success(p) {
		mylat =  p.coords.latitude;
	  	mylong = p.coords.longitude;
	
		myfinallat = mylat.toFixed(2);
		myfinallong = mylong.toFixed(2);

		var resturl = escape("http://free.worldweatheronline.com/feed/weather.ashx?q=")+myfinallat+escape(",")+myfinallong+escape("&format=xml&key=e8535739e1055006111409");
		console.log(resturl);
		
		var mylocation = escape("http://where.yahooapis.com/geocode?q=")+mylat+escape(",")+mylong+escape("&gflags=R&appid=[yourappidhere]");
		console.log(mylocation);
		
		Temp.apiGetToken(resturl);
		Myloc.apiGetToken(mylocation);	

	}

	function geo_error() {
	  alert("Could not find your Location! Seems that your location service is off");
	}
	
});

$('#home-page').live('pageinit', function(){
	localStorage.clear();
});



//****************************************//
// Proxy to get the value from google API //
//****************************************//


var Proxy = { 
  proxyScript: "api.php", // relative to document root
  /*
    Options:
    url: remote api URL
    type: type of request ('get' or 'post')
    data: object with key: value pairs (eg: {keyname: value, …}
    dataType: returned data type from the api
    async: set to false to make it wait
    success: function pointer for success
    error: function pointer for error
    header: show header (1 or 0, default is 0)
  */
  a: function(options) {
    var u = options.url, 
        t = options.type, 
        d = options.data, 
        dt = options.dataType, 
        ac = options.async, 
        scb = options.success,
        ecb = options.error;
        h = options.header;

    var url = '';
    if(u == undefined)
      return false;
    if(t == undefined)
      t = 'get';
    if(d == undefined) // d should be an object {key: value, ...}
      d = {};
    if(dt == undefined)
      dt = 'text';
    if(ac == undefined)
      ac = true;
    if(scb == undefined) // success function pointer
      scb = function() {}
    if(ecb == undefined) // error function pointer
      ecb = function() {}
    if(h == undefined)
      h = 0;
    
    url = u;
    t = t.toLowerCase();
    var dataString = '';
    
    for(i in d) {
      dataString += '&data[' + i + ']=' + d[i];
    }

    $.ajax({
      type: 'POST',
      url: Proxy.proxyScript,
      data: "action=request&host=" + url + "&type=" + t + "" + dataString + "&dataType=" + dt + "&header=" + h,
      dataType: dt,
      async: ac,
      success: function(res, status, XMLHttpRequest) {
        scb(res, status, XMLHttpRequest);
      },
      error: function() {
        ecb(res, status, XMLHttpRequest);
      }
    });
  }
  
  
};


