/*
########################### anthrazit ag ############################
### +-----------------------------------------------------------+ ###
### |      Project Name: moPage                                 | ###
### |      Author: Stalder, Lukas                               | ###
### |      Datum: 03.01.2012                                    | ###
### |      (c) anthrazit ag, Zuerich                            | ###
### +-----------------------------------------------------------+ ###
#####################################################################
*/

// JAVASCRIPT Lib



function getElement(id){
	var obj;
	if (document.getElementById){
		obj = document.getElementById(id);	
	}else if (document.all){
		obj = document.all.id;	
	}
	return obj;
}


function countChars(obj, displayid){
	var mlength = obj.getAttribute? parseInt(obj.getAttribute("maxlength")) : "";
	if (obj.getAttribute && obj.value.length > mlength){
		obj.value = obj.value.substring(0, mlength);
	}
	if (displayid){
		var disp = getElement(displayid);
		disp.innerHTML = (mlength - obj.value.length);
	}
}


// simple jquery seconds countdown
if(typeof(jQuery) !== 'undefined'){
	(function($) {
	
		$.fn.reloadafter = function(options) {
	
			var settings	= { seconds:60};	
			$.extend(settings,options);
		
			var interval = 1000;
			var secs	= settings.seconds + 1;
			var target		= $(this);
			
			var remainingTime = function() {
				secs--;			
				if (secs < 1){
					 counterStop();
					 window.location.href = settings.url;
					 secs = 1;
				}
				
				var m = Math.floor(secs / 60);
				var s = secs % 60;
				
				
				if (m > 0) counter = m + " min " + s + " sek"; 
				else counter = secs + " sek ";
				return counter;
			}
			
			var counterUpdate = function() {
				target.html(remainingTime());
			}
			
			
			var counterStart = function() {
				counterUpdate();
				executer = setInterval(function() {counterUpdate()},interval);
			}
			
			var counterStop = function() {
				clearInterval(executer);
			}
			
			if (secs > 0) {
				counterStart()
			}
	
		};
	
	})(jQuery);
}



function rawurldecode( str ) {
    // Decodes URL-encodes string  
    // 
    // version: 901.1411
    // discuss at: http://phpjs.org/functions/rawurldecode
    // +   original by: Brett Zamir
    // *     example 1: rawurldecode('Kevin+van+Zonneveld%21');
    // *     returns 1: 'Kevin+van+Zonneveld!'
    // *     example 2: rawurldecode('http%3A%2F%2Fkevin.vanzonneveld.net%2F');
    // *     returns 2: 'http://kevin.vanzonneveld.net/'
    // *     example 3: rawurldecode('http%3A%2F%2Fwww.google.nl%2Fsearch%3Fq%3Dphp.js%26ie%3Dutf-8%26oe%3Dutf-8%26aq%3Dt%26rls%3Dcom.ubuntu%3Aen-US%3Aunofficial%26client%3Dfirefox-a');
    // *     returns 3: 'http://www.google.nl/search?q=php.js&ie=utf-8&oe=utf-8&aq=t&rls=com.ubuntu:en-US:unofficial&client=firefox-a'
    var histogram = {};
    var ret = str.toString(); 

    var replacer = function(search, replace, str) {
        var tmp_arr = [];
        tmp_arr = str.split(search);
        return tmp_arr.join(replace);
    };

    // The histogram is identical to the one in urlencode.
    histogram["'"]   = '%27';
    histogram['(']   = '%28';
    histogram[')']   = '%29';
    histogram['*']   = '%2A';
    histogram['~']   = '%7E';
    histogram['!']   = '%21';

    for (replace in histogram) {
        search = histogram[replace]; // Switch order when decoding
        ret = replacer(search, replace, ret) // Custom replace. No regexing
    }

    // End with decodeURIComponent, which most resembles PHP's encoding functions
    ret = decodeURIComponent(ret);

    return ret;
}



function getGeoLocation(url_reload, msg_fail)
{
    if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {

			// get current cookies
			//var current_cookies = get_cookies_array();
			
			// if values chnaged, store new values in cookies an force browser to reload
			//if ( position.coords.latitude != current_cookies['latitude'] && position.coords.longitude != current_cookies['longitude']){
			
				var the_date = new Date(2038, 1, 1, 0, 0, 0, 0);
				
				var the_cookie = 'geoLatitude='+ position.coords.latitude + ';expires=' + the_date.toGMTString() + ';path=/';
				document.cookie = the_cookie;	
				
				var the_cookie = 'geoLongitude='+ position.coords.longitude + ';expires=' + the_date.toGMTString() + ';path=/';
				document.cookie = the_cookie;
				
			//}
			
		});
				
    }else{
		alert(msg_fail);
	}
	if (url_reload != false) window.location.href = url_reload;
}

// try to get cords from current location and redirect to given URL and replace {lat} {long} by retrieved coords
function getGeoLocationRedirectCoords(url_reload, msg_fail)
{
    if (navigator.geolocation) {
		navigator.geolocation.getCurrentPosition(function(position) {

	
		var the_date = new Date(2038, 1, 1, 0, 0, 0, 0);
		
		var the_cookie = 'geoLatitude='+ position.coords.latitude + '; expires=' + the_date.toGMTString() + '; path=/';
		document.cookie = the_cookie;	
		
		var the_cookie = 'geoLongitude='+ position.coords.longitude + '; expires=' + the_date.toGMTString() + '; path=/';
		document.cookie = the_cookie;
		
		// redirect to given url and replace lat /long
		if (url_reload != false){
			url_reload = url_reload.replace("{lat}", position.coords.latitude);
			url_reload = url_reload.replace("{long}", position.coords.longitude);
			//alert(url_reload);
			window.location.href = url_reload;
		}
		});
		
    }else{
		alert(msg_fail);
	}
}

// get all cookies
function get_cookies_array() {
    var cookies = { };
    if (document.cookie && document.cookie != '') {
        var split = document.cookie.split(';');
        for (var i = 0; i < split.length; i++) {
            var name_value = split[i].split("=");
            name_value[0] = name_value[0].replace(/^ /, '');
            cookies[decodeURIComponent(name_value[0])] = decodeURIComponent(name_value[1]);
        }
    }
    return cookies;   
}




