function setCookie(c_name,value,exdays){
	var exdate=new Date();
	exdate.setDate(exdate.getDate() + exdays);
	var c_value=escape(value) + ((exdays==null) ? "" : "; expires="+exdate.toUTCString());
	document.cookie=c_name + "=" + c_value;
}

function getCookie(c_name){
	var i,x,y,ARRcookies=document.cookie.split(";");
	var result = "null";
	for (i=0;i<ARRcookies.length;i++){
		x=ARRcookies[i].substr(0,ARRcookies[i].indexOf("="));
		y=ARRcookies[i].substr(ARRcookies[i].indexOf("=")+1);
		x=x.replace(/^\s+|\s+$/g,"");
		if (x==c_name){
			result = unescape(y);
			return result;
		}
	}
	return result;
}

function readFileAndSetCookie(url, cookieName){
	$.ajax({
		async: false,
		type: 'GET',
		url: url,
		success: function(data) {
			setCookie(cookieName, data, 30);
		}
	});
}

function getPageName(url){
	if (url) {
		var m = url.toString().match(/.*\/(.+?)\./);
		if (m && m.length > 1) {
			return m[1];
		}
	}
	return ("");
}

function GetQueryString(name){
	var reg = new RegExp("(^|&)"+ name +"=([^&]*)(&|$)");
	var r = window.location.search.substr(1).match(reg);
	if (r !== null){
		return unescape(r[2]);
	}else{
		return null;
	}
}

function childData(selector, arg){
	return selector.find(arg).attr('data');
}

function lookupZip(zip){
		$.ajax({
				async: false,
				type: 'GET',
				url: '/bin_netadvance/getLatLong.a4p',
				data: {'zip' : zip},
				dataType : 'json',
				success: function(data) {
					setCookie('geo_lat', data.latitude, 30);
					setCookie('geo_long', data.longitude, 30);
				}
		});
}

function setLocalElements(){
	
	
	$('#locMainPhoto').attr('src', getCookie('geo_dir') + '/mainphoto.jpg');
	$('#locMainPhoto').show(); // show, becuase it defaults to display: none in the CSS file
	$('#locAreaTag').html(getCookie('_area'));
	$('#locServingTag').html(getCookie('_serving'));
	$('#locExpressionText').html(getCookie('_exp'));
	$('#locAmtTag').html('Email FREE Listing Flyers to ' + getCookie('_serving') + ' Agents!'); // AMT
}

function updateCookies(dir, type, zip, lat, long){
	setCookie('geo_dir', dir, 30);
	setCookie('geo_dirType', type, 30);
	setCookie('geo_zip', zip, 30);
	setCookie('geo_lat', lat, 30);
	setCookie('geo_long', long, 30);

	setCookie('_area', getCookie('_area'), 30);
	if (getCookie('_area') === 'null'){
		readFileAndSetCookie(dir+'/areaname.txt', '_area');
	}

	setCookie('_serving', getCookie('_serving'), 30);
	if (getCookie('_serving') === 'null'){
		readFileAndSetCookie(dir+'/servingtag.txt', '_serving');
	}

	setCookie('_exp', getCookie('_exp'), 30);
	if (getCookie('_exp') === 'null'){
		readFileAndSetCookie(dir+'/expression.txt', '_exp');
	}
	
	if (zip === ''){
		if(type === 'area' || type === 'metro'){
			readFileAndSetCookie(dir + '/ziptag.txt', 'geo_zip');
			lookupZip(data);
		}
	}
}

//Weather START
function getTime(){
	var a_p = "";
	var d = new Date();
	var curr_hour = d.getHours();
	if (curr_hour < 12){
		a_p = "AM";
	}else{
		a_p = "PM";
	}
	if (curr_hour === 0){
		curr_hour = 12;
	}
	if (curr_hour > 12){
		curr_hour = curr_hour - 12;
	}
	var curr_min = d.getMinutes();
	curr_min = curr_min + "";
	if (curr_min.length === 1){
		curr_min = "0" + curr_min;
	}
	return (curr_hour + ":" + curr_min + " " + a_p);
}

function weatherAPI(where){
	$.ajax({
		type: "GET",
		data:"where="+where,
		//data:"where=78732", //testing
		dataType:"xml",
		url: "/includes/local/weather/google-weather.php",
		success: function(data){
			function addForecastDiv( day, icon, condition, low, high ){
				daydiv = $("<div class='day'></div>");
				daydiv.append( "<div class='name'>" + day + "</div>" );
				daydiv.append( "<img src='http://www.google.com/" + icon + "' />" );
				daydiv.append( "<div class='temp'>" + low + "</div>");
				daydiv.append( "<div class='temp'>" + high + "</div>");
				daydiv.append( "<div class='condition'>" + condition + "</div>" );
				$("#wbForecast").append(daydiv);	
			}
			
			forecast	= $(data).find('forecast_information');
			cCondition	= $(data).find('current_conditions');
			city	= childData(forecast, 'city');
			
			if(city !== undefined){
				date	= childData(forecast, 'forecast_date');
				tempF	= childData(cCondition, 'temp_f');
				condition	= childData(cCondition, 'condition');
				humidity	= childData(cCondition, 'humidity');
				wind	= childData(cCondition, 'wind_condition');
				icon	= childData(cCondition, 'icon');
				
				if (getCookie('geo_dirType') == "metro" || getCookie('geo_dirType') == "area"){
					$('#wbCity').html(getCookie('_area')); // WB Heading from cookie
				}else{
					$('#wbCity').html(city); // WB Heading from google
				}
				$('#wbCurrentCond img').attr({'src':'http://www.google.com'+icon});
				$('#wbCurCondition').text(condition);
				$('#wbHumidity').text(humidity);
				$('#wbWind').text(wind);
				$('#wbTempF').text(tempF);
				$('#wbDate').text($.date(date, "yyyy-mm-dd").format("MMMM d, yyyy"));
				$('#wbTime').html(getTime()); // WB Heading	
			
				$(data).find('forecast_conditions').each(function(){
					addForecastDiv(
						$(this).find('day_of_week').attr('data'),
						$(this).find('icon').attr('data'),
						$(this).find('condition').attr('data'),
						'Low: ' + $(this).find('low').attr('data'),
						'High: ' + $(this).find('high').attr('data')
					);
				});
			}else{
				//alert("Could not find the weather for " + where);
			}
		}
	});
}
//Weather END


// check if cookies exist
function geoLookup(){

	if (getCookie('geo_dir') === 'null'){
		var queryIp = GetQueryString('ip'); // for testing mostly ... did i pass a url parameter?
		var ip = '';
		if (queryIp !== null) { // no parameter passed ... get IP from geo.a4d and run the geo lookup
			ip = queryIp;
		}
		// Run the lookup
		$.ajax({
			async: false,
			type: 'GET',
			url: '/bin_netadvance/geo.a4p',
			data: {'ip' : ip},
			dataType: 'json',
			error: function(){
				// do popup stuff here ...
				window.location = '/changecity.html';
			},
			success: function(data){
				if (data.dir === 'default'){
					window.location = '/changecity.html';
				}else{
					readFileAndSetCookie(data.dir+'/areaname.txt', '_area');
					readFileAndSetCookie(data.dir+'/servingtag.txt', '_serving');
					readFileAndSetCookie(data.dir+'/expression.txt', '_exp');
					
					if (data.zip === ''){// update zip if necessary
						if (data.type === 'metro' || data.type === 'area') {
							readFileAndSetCookie(data.dir+'/ziptag.txt', 'geo_zip');
							data.zip = getCookie('geo_zip'); // since it was blank, we need to set it now
						}
					}
					updateCookies(data.dir, data.type, data.zip, data.lat, data.long);
					setLocalElements();
					var pagename = getPageName(window.location.pathname);
					if ((pagename === '') || (pagename === 'index')) {
						weatherAPI(encodeURI(getCookie('geo_zip')));
						$('#grouponAdContainer').fadeIn(); // show, becuase it defaults to display: none in the CSS file
					}
				}
			}
		});
	}else{
		updateCookies(getCookie('geo_dir'), getCookie('geo_dirType'), getCookie('geo_zip'), getCookie('geo_lat'), getCookie('geo_long'));
		setLocalElements();
		var pagename = getPageName(window.location.pathname);
		if ((pagename === '') || (pagename === 'index')) {
			weatherAPI(encodeURI(getCookie('geo_zip')));
			$('#grouponAdContainer').fadeIn(); // show, becuase it defaults to display: none in the CSS file
		}
	}
}

$(function(){
	geoLookup();	
});


