/**
 * @author botonddani
 */
$(document).ready(function(){
	window.bUrl = getBaseUrl();
	window.myConquests = false;
	window.act = $("#activity").val();
	
	$("#menu"+"-box").hide();
	
	//set/get session_id
	sessid = $("#session_id").val();
	advzsessid = readCookie('advzsessid');
	if(!sessid || advzsessid != sessid) {
		$.post(window.bUrl+"/ajax/sess-id/id/"+advzsessid, {}, function(data){		
			createCookie('advzsessid', data.id, 100);
		}, 'json');
	}
	
	//set mesure unit
	window.mesure_unit = $("#mesure_unit").val();
	if(mesure_unit == 0) {
		//an anonymus accont - find which state is from an set imperial / metric system
		advzmesunit = readCookie('advzmesunit');
		if(!advzmesunit) {
			//unit = 
			//if(google.loader.ClientLocation.address.country_code == 'US' || google.loader.ClientLocation.address.country_code == 'GB') {
			if(google.loader.ClientLocation.address.country_code == 'US') {
				advzmesunit = 'imperial';
			} else {
				advzmesunit = 'metric';
			}
			createCookie('advzmesunit', advzmesunit, 100);
		}
		window.mesure_unit = advzmesunit;
	}
	
	
	$("#login_box input").focus(function(){
		$(this).parent().find("span").hide();
	});
	$("#login_box input").blur(function(){
		if ($(this).val() == "") {
			$(this).parent().find("span").show();
		}
	});
	$(".box1 tr").hover(function(){ $(this).addClass("current"); }, function(){ $(this).removeClass("current"); });
	var userAgent = navigator.userAgent.toLowerCase();
	 
	// Figure out what browser is being used
	jQuery.browser = {
		version: (userAgent.match( /.+(?:rv|it|ra|ie|me)[\/: ]([\d.]+)/ ) || [])[1],
		chrome: /chrome/.test( userAgent ),
		safari: /webkit/.test( userAgent ) && !/chrome/.test( userAgent ),
		opera: /opera/.test( userAgent ),
		msie: /msie/.test( userAgent ) && !/opera/.test( userAgent ),
		mozilla: /mozilla/.test( userAgent ) && !/(compatible|webkit)/.test( userAgent )
	};
	
	$(function(){
		/* Select */
		$(".trails_page span.r_state").css({ "width" :  "58px" });
		$(".trails_page span.r_region").css({ "width" :  "160px" });

		if($.browser.safari) {
			$(".state-select").css({"width" : "60px"});
			$(".region-select").css({"width" : "160px"});
			$(".textbox").css({"padding":"1px 7px 0px 27px"});
		}	
		if($.browser.chrome) { 
			$(".state-select").css({"width" : "45px"});
			$(".textbox").css({"padding":"1px 7px 0px 27px"});
		}	
		if($.browser.opera) { 
			$(".state-select").css({"width" : "60px"});
			$(".textbox").css({"padding":"0px 7px 0px 27px"});
		}	
		if($.browser.msie) { 
			if(jQuery.browser.version.substr(0, 1) == "7") {
				$(".state-select").css({"width" : "60px"});
				$(".region-select").css({"width" : "190px"});
			} else {
				$(".state-select").css({"width" : "85px"});
				$(".region-select").css({"width" : "210px"});
			}
		}
		
		if($("#email").val()) $("#email").parent().find("span").hide();
		if($("#password").val()) $("#password").parent().find("span").hide();

	});
	
	$(".trails_page #container_top label select").change(function(){
		$(this).parent().children("span.content").text($(this).find("option:selected").text());
		search_obj['state_name'] = $("#state_id").prev().html();
		search_obj['region_name'] = $("#region_id").prev().html();
	});


	
	advzactions = readCookie('advzactions');
	if(!advzactions) {
		createCookie('advzactions', 5, 1);
	}
		

});


function updateTips(t, id) {
	$(".validateTips-"+id).text(t).addClass('errorMsg');
}
function checkLength(o,n,min,max) {
	if ( o.val().length > max || o.val().length < min ) {
		o.addClass('ui-state-error');
		updateTips("Length of " + n + " must be between "+min+" and "+max+".");
		return false;
	} else {
		return true;
	}
}


function formatFloat(aFloat, aPrecision){
	var thousand_sep = ",";
	var decimal_point = ".";
	var default_precision = 2;
	
	try {
		precision = default_precision;
		if(!isNaN(aPrecision))
			if(Math.abs(aPrecision)<=10)
				precision = aPrecision;
	} catch(e) {
		precision = default_precision;
	}
	try {
		number = parseFloat(aFloat+'');
		if(isNaN(number))
			return "0";
	} catch(e) {
		return "0";
	}
	
	number = Math.round(number * Math.pow(10, precision)) / Math.pow(10, precision);
	integerpart = '' + ((number<0) ? Math.ceil(number) : Math.floor(number));
	decimalpart = Math.abs(Math.round((number - integerpart)*(Math.pow(10, precision))));
	if(decimalpart<10)
		decimalpart="0"+decimalpart;
	if(decimalpart==0)
		decimalpart="00";
	var buff = "";
	for(j=-1, ind=integerpart.length; ind>=0; ind--, j++){
		if((j%3) == 0 && j>1)
			buff = thousand_sep + buff;
		buff = integerpart.charAt(ind) + buff;
	}
	if(precision>0 && decimalpart != '00')
		return buff+decimal_point+decimalpart;
	return buff;
}

function formatInt(aInt){
	return formatFloat(aInt,0);
}

function str_replace (search, replace, subject, count) {
    f = [].concat(search),
    r = [].concat(replace),
    s = subject,
    ra = r instanceof Array, sa = s instanceof Array;    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
     for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {            
        	temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}        }
    }
    return sa ? s : s[0];
}

function formatPhone(phone) {
	phone = phone.replace(/[^0-9]*/gi, "");
	return '('+phone.substr(0,3)+')'+phone.substr(3,3)+'-'+phone.substr(6,4);
}



function loadRegions(type, val, all, region_id) {
	var_state = $("#state_id").val();
	
	//console.log('aaa'+var_state);
	//load regions
	$.post(window.bUrl+"/ajax/load-regions/state_id/"+var_state+"/act/"+window.act+'/all/'+all, {}, function(response){
		var options = '';
		
		data = evaluate(response);
		
		nfp = data.nfp;
		nfpr = data.allregions;
		data = data.regions;

		if(data.length) {
			options += '<option value="">Region</option>';	
			for (var i = 0; i < data.length; i++) {
				selected = data[i].region_id == region_id ? 'selected="selected"' : '';
				options += '<option value="' + data[i].region_id + '" '+selected+'>' + trim(data[i].region_name, " \n\r") + '</option>';
			}
			$("#region_id").html(options); 
		} else {
			options = '<option value="">Region</option>';
			$("#region_id").html(options); 
		}
		$("#region_id").parent().find("span").text('Region');
		
		
		
		if(nfp.length) {
			options = '<option value="">National Forests/Parks</option>';
			for (i = 0; i < nfp.length; i++) {
				selected = nfp[i].region_id == region_id ? 'selected="selected"' : '';
				options += '<option value="' + nfp[i].region_id + '" '+selected+'>' + trim(nfp[i].region_name, " \n\r") + '</option>';
			}
			$("#nfp_id").html(options); 
		} else {
			options = '<option value="">National Forests/Parks</option>';
			$("#nfp_id").html(options); 
		}
		
		
		
		if(nfpr.length) {
			options = '<option value="">Regions</option>';
			c1 = nfpr.length;
			reg_name = '';
			for(i1=0; i1 < c1; i1++) {
				options += '<optgroup label="'+nfpr[i1].label+'">';	
				c2 = nfpr[i1].arr.length;
				for(i2=0; i2 < c2; i2++) {
					selected = nfpr[i1].arr[i2].region_id == region_id ? 'selected="selected"' : '';
					if (selected != '') 
						reg_name = trim(nfpr[i1].arr[i2].region_name);
					options += '<option value="' + nfpr[i1].arr[i2].region_id + '" '+selected+'>' + trim(nfpr[i1].arr[i2].region_name, " \n\r") + '</option>';
				}
				options += '</optgroup>';
			}
			$("#region_id").html(options); 
			if(reg_name != '')
				$("#region_id").prev().html(reg_name);
			else	
				$("#region_id").prev().html("Regions");
		} 

		if(type == 'tid') {
			$("#region_id").val(val);
			
			act_id = $("#act_id").val();
			search();
			
			detailActivity(act_id);  
			
			$("#status-advertise").hide();
			$("#all-trails, #trail-report, #trail-status, #trail-photos, #google-map").show();
		}	
		
		if(type == 'autoload') {
			autoloadRegions(val);			
		}
	});
}

function loadStates() {
	country = $("#country").val();
	$.post(window.bUrl+"/ajax/load-states/country/"+country+"/act/"+window.act, {}, function(data){
		var options = '';
		
		data = evaluate(data);
		
		if(data.length) {
			options += '<option value="">State</option>';	
			for (var i = 0; i < data.length; i++) {
				options += '<option value="' + data[i].id + '">' + data[i].state + '</option>';
			}
		} else {
			options = '<option value="">State</option>';
		}
		//alert(options);
		$("#state_id").html(options); 		
	});
	
}

function getBaseUrl() {
	return $("#baseUrl").val();
}

function hasIdentity() {
	if(!$("#hasIdentity").val()) {
		if(confirm('You have to be registered first. Login now?')) {
			document.location = window.bUrl + '/login';
			return 0;
		}else	
			return 0;
	}
	return 1;
}
function in_array (needle, haystack) {
    for (key in haystack) {
        if (haystack[key] == needle) {
            return true;
        }
    }
   return false;
}

function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		expires = "; expires="+date.toGMTString();
	}
	else expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}

function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}

function eraseCookie(name) {
	createCookie(name,"",-1);
}

function parseAjaxResponse(data) {
	rowd = eval('('+data+')');
	messageBox(rowd.message);
	return rowd.json;
}

function messageBox(msg) {
	$("#dispaly-feed").text(msg);
	$("#dispaly-feed").show();
	var t=setTimeout("$('#dispaly-feed').hide('slow');",2000);
}

function limitMyActions() {
	advzactions = readCookie('advzactions');
	if($("#hasIdentity").val()) return 1;
	if(advzactions > 0) {
		advzactions--;	
		createCookie('advzactions', advzactions, 1);
		return 1;	
	} else {
		if(confirm("In order to make more ratings you have to be a registered user. Sign up or Log in now?"))
		document.location = window.bUrl + '/login';
	}
	return 0;	
}

function unitConvert(val, unit, type) {
	var convertor = {"ft":{"name":'m',"val":'0.3048'},"mi":{"name":'km',"val":'1.609344'},"acres":{"name":'ha',"val":'0.40468564224'}};

	mesureUnit = window.mesure_unit;

	if(mesureUnit == 'metric') {	
		val = val * convertor[unit].val;
		unit = convertor[unit].name;
	} 	

	if(val == '')
		return unit;
	else {
		if(type == 'int')   
			return formatFloat(val, 0) + ' ' + unit;
		else
			return formatFloat(val, 2) + ' ' + unit;
	}
}

function getDrivingTime(tid, gzip, glat, glong, type){
	geocoder = new GClientGeocoder();
	
	$.post(window.bUrl+"/ajax/query-drive-time/act_id/"+tid+'/zip/'+gzip, {}, function(data){
		data = evaluate(data)
		if(data.time == 0) {
			//if time is 0 then we do  a google request and save the time
			geocoder.getLatLng(gzip, function(point) {
		        if (!point) {
		        	alert(gzip + " is not a valid zip.");
		        } else {
		        	pointTo = new GLatLng(glat, glong);
					gdirPoints = new GDirections();
					GEvent.addListener(gdirPoints, "load", function(){
						 dir = gdirPoints.getDuration(); 
						 if (dir) {
							time = dir.seconds/60;
							if(type == 'edit_menu') {
								$(".loading_div").hide();
								$("#google_results").html(" Driving time: "+display_time(time));
							} else if(type == 'compare') {
								$("#drive-time-result"+arr[2]).html(display_time(time));
							}
							//save the time
							$.post(window.bUrl+"/ajax/save-driving-time/act_id/"+tid+'/zip/'+gzip+'/time/'+time, {}, function(data){
							});
						 }	
					});
					var loadString = "from: " + point + " to: " + pointTo;
					gdirPoints.load(loadString, {getPolyline:false,getSteps:false});
		        }
			}); 
		} else {
			//we get the time from db, we display it
			time = data.time;
			if(type == 'edit_menu') {
				$(".loading_div").hide();
				$("#google_results").html(" Driving time: "+display_time(time));
			} else if(type == 'compare') {
				$("#drive-time-result"+arr[2]).html(display_time(time));
			}			
		}
	});	
}

function trim(str, chars) {
	return ltrim(rtrim(str, chars), chars);
}
 
function ltrim(str, chars) {
	chars = chars || "\\s";
	return str.replace(new RegExp("^[" + chars + "]+", "g"), "");
}
 
function rtrim(str, chars) {
	chars = chars || "\\s";
	if (str && str.length>0)
		return str.replace(new RegExp("[" + chars + "]+$", "g"), "");
	else
		alert('nimik');
}

function evaluate(response) {
	response = eval('('+response+')');
	if(response.msg != '')
		messageBox(response.msg)
	if(response.success == 0)  
		return

	return response.result;
}





