
var ws_timedblock = {};

// timers
ws_timedblock._timers = {};


// namespaces
ws_timedblock.main = {};
ws_timedblock.cookietools = {};
ws_timedblock.viewtools = {};
ws_timedblock.timerdata = {};
ws_timedblock.timertools = {};



//
// Public method (the one and only)
//
ws_timedblock.register = function( id, time_hours, time_minutes, start_type ) {
	ws_timedblock._timers[id] = {
		'id': id, 
		'started':false, 
		'finished':false, 
		'element_running': 'timedblock_running_'+id, 
		'element_finished': 'timedblock_finished_'+id,
		'element_timer': 'timedblock_timer_'+id,
		'time_hours': time_hours,
		'time_minutes': time_minutes,
		'start_type': start_type
	};
}



//
// Main methods
//
ws_timedblock.main.check_timers_are_actionnable = function(startup) {
	if (!ws_timedblock._timers) {
		return ;	
	}
	for(var id in ws_timedblock._timers) {
		
		if (ws_timedblock.timerdata.isTimerStarted(id)) {
			continue;
		}
		
		if (startup && (date = ws_timedblock.cookietools.getStartedCookieDate(id))) {
			ws_timedblock.timerdata.setTimerStarted(id);
			ws_timedblock.timertools.startDhmlTimer(id,date);
			continue;
		}
		
		if (ws_timedblock.timerdata.isTimerFinished(id)) {
			continue;
		}
		if (ws_timedblock.cookietools.hasFinishedCookie(id)) {
			ws_timedblock.main.markAsFinished(id);
			continue;
		}
		
		var el = ws_timedblock.timerdata.getRunningElement(id);
		if ( ( startup && ws_timedblock.timerdata.mustAlwaysStartOnLoad(id) )
			 || 
			 (ws_timedblock.viewtools.isVisible(el))) {
			ws_timedblock.timerdata.setTimerStarted(id);
			ws_timedblock.cookietools.storeStartedCookie(id);
			ws_timedblock.timertools.startDhmlTimer(id,null);
			continue;
		} 
	}
}

ws_timedblock.main.markAsFinished = function(id) {
	ws_timedblock.timerdata.getRunningElement(id).style.display ='none'; 
	ws_timedblock.timerdata.getFinishedElement(id).style.display ='block'  
	ws_timedblock.cookietools.storeFinishedCookie(id);
	ws_timedblock.timerdata.setTimerFinished(id);
}



//
// Timer data related
// 

ws_timedblock.timerdata.isTimerStarted = function(id) {
	return ws_timedblock._timers[id]['started'];
}

ws_timedblock.timerdata.setTimerStarted = function(id) {
	ws_timedblock._timers[id]['started'] = true;
}

ws_timedblock.timerdata.isTimerFinished = function(id) {
	return ws_timedblock._timers[id]['finished'];
}


ws_timedblock.timerdata.setTimerFinished = function(id) {
	ws_timedblock._timers[id]['element_finished'] = true;
}

ws_timedblock.timerdata.getRunningElement = function(id) {
	return document.getElementById(ws_timedblock._timers[id]['element_running']);
}

ws_timedblock.timerdata.getFinishedElement = function(id) {
	return document.getElementById(ws_timedblock._timers[id]['element_finished']);
}

ws_timedblock.timerdata.getMinutes = function(id) {
	return ws_timedblock._timers[id]['time_minutes'];
}

ws_timedblock.timerdata.getHours = function(id) {
	return ws_timedblock._timers[id]['time_hours'];
}

ws_timedblock.timerdata.getStartType = function(id) {
	return ws_timedblock._timers[id]['start_type'];
}


ws_timedblock.timerdata.mustAlwaysStartOnLoad = function(id) {
	return ws_timedblock._timers[id]['start_type'] == 'onload';
}



//
// Timer (dhtml) related
//
ws_timedblock.timertools.startDhmlTimer = function( id, alreadyStartedDate ) {
	
	var minutes = ws_timedblock.timerdata.getMinutes(id);
	var hours = ws_timedblock.timerdata.getHours(id);
	
	var layout = '{mn} Minute(n) {sn} Sekunde(n)'; // Stunden
	if (hours) {
		layout = '{hn} Stunde(n) {mn} Minute(n) {sn} Sekunde(n)'; // Stunden
	}
	
	if (alreadyStartedDate) {
		var untildate = new Date();
		var currentdate = new Date();
		untildate.setTime(alreadyStartedDate.getTime()+(1000*60*minutes)+(60*60*1000*hours));
		if (currentdate.getTime() > untildate.getTime()) {
			ws_timedblock.main.markAsFinished(id);
			return ;		
		} 
		var until = untildate;
	} else {
		if (hours) {
			var until = '+'+hours+'h'+minutes+'m';
		} else {
			var until = '+'+minutes+'m';
		}
	}
	//until = '+5';
	var f = function() {
		ws_timedblock.main.markAsFinished(id);
	};
	$("#timedblock_timer_"+id).countdown({'until': until, 'layout': layout, onExpiry: f });

}

//
// View related
//

ws_timedblock.viewtools.isVisible = function(el) {
  
  var top = el.offsetTop;
  var left = el.offsetLeft;
  var width = el.offsetWidth;
  var height = el.offsetHeight;

  
  while(el.offsetParent) {
    el = el.offsetParent;
    top += el.offsetTop;
    left += el.offsetLeft;
  }

  var wp = ws_timedblock.viewtools.getWindowStatus();
  return (
    top < (wp.sy + wp.winHt) &&
    left < (wp.sx + wp.winWh) &&
    (top + height) > wp.sy &&
    (left + width) > wp.sx
  );

}

ws_timedblock.viewtools.getWindowStatus = function() {
	var result = {'winHt': 0, 'winWh': 0, 'sy': 0, 'sx': 0};
	
	if (window.innerHeight) { 
		result.winHt = window.innerHeight-18;
		result.winWh = window.innerWidth;
	} else if (document.documentElement && document.documentElement.clientHeight) {
		result.winHt = document.documentElement.clientHeight;
		result.winWh = document.documentElement.clientWidth;
	}else if (document.body && document.body.clientHeight) {
		result.winHt = document.body.clientHeight;
		result.winWh = document.body.clientWidth;
	}
	

	if (document.documentElement && document.documentElement.scrollTop) {
		result.sy = document.documentElement.scrollTop;
		result.sx = document.documentElement.scrollLeft;
	} else if (document.body && document.body.scrollTop) {
		result.sy = document.body.scrollTop; 
		result.sx = document.body.scrollLeft; 
	}else if (window.pageYOffset) {
		result.sy = window.pageYOffset;
	} else if (window.scrollY) {
		result.sy = window.scrollY;
		result.sx = window.scrollX;
	}

	return result;
}



//
// Cookie related
//



// Main cookie related functions
// 1. Cookie Finished
ws_timedblock.cookietools.storeFinishedCookie= function(id) {
	ws_timedblock.cookietools.setCookie('timedblock_'+id,'finished',ws_timedblock.cookietools.getExpDate(800,0,0),'/',window._domain);
}

ws_timedblock.cookietools.hasFinishedCookie = function(id) {
	var val = ws_timedblock.cookietools.getCookie('timedblock_'+id);
	if (val == 'finished') {
		return true;
	}
	
	return false;
}
// 2. Cookie Started
ws_timedblock.cookietools.storeStartedCookie= function(id) {
	var date = new Date();
	var str = date.getTime();
	ws_timedblock.cookietools.setCookie('timedblock_started_'+id,str,ws_timedblock.cookietools.getExpDate(800,0,0),'/',window._domain);
}


ws_timedblock.cookietools.getStartedCookieDate=function(id) {
	var val = ws_timedblock.cookietools.getCookie('timedblock_started_'+id);
	if (!val) {
		return false;
	}
	var date = new Date();
	date.setTime(val);
	return date;
}



// Generic cookie functions
ws_timedblock.cookietools.setCookie = function(name, value, expires, path, domain, secure) {
    document.cookie = name + "=" + encodeURI(value) +
        ((expires) ? "; expires=" + expires : "") +
        ((path) ? "; path=" + path : "") +
        ((domain) ? "; domain=" + domain : "") +
        ((secure) ? "; secure" : "") ;
}


ws_timedblock.cookietools.getCookie = function(name) {
	 var arg = name + "=";
    var alen = arg.length;
    var clen = document.cookie.length;
    var i = 0;
    while (i < clen) {
        var j = i + alen;
        if (document.cookie.substring(i, j) == arg) {
            return ws_timedblock.cookietools.getCookieVal(j) ;
        }
        i = document. cookie. indexOf(" ", i) + 1;
        if (i == 0) break;
    }
    return "";
}

ws_timedblock.cookietools.getCookieVal= function(offset) {
    var endstr = document.cookie.indexOf ("; ", offset) ;
    if (endstr == -1) {
        endstr = document.cookie.length;
    }
     return decodeURI(document. cookie. substring(offset, endstr));
}

// utility function to retrieve an expiration date in proper
// format; pass three integer parameters for the number of days, hours,
// and minutes from now you want the cookie to expire (or negative
// values for a past date) ; all three parameters are required,
// so use zeros where appropriate
ws_timedblock.cookietools.getExpDate = function(days, hours, minutes) {
    var expDate = new Date( );
    if (typeof days == "number" && typeof hours == "number" &&
        typeof minutes == "number") {
        expDate.setDate(expDate.getDate( ) + parseInt(days));
        expDate.setHours(expDate.getHours( ) + parseInt(hours));
        expDate.setMinutes(expDate.getMinutes( ) + parseInt(minutes));
        return expDate.toUTCString( );
    }
}


//
// Registering listeners
//


$(document).ready(function() {
	ws_timedblock.main.check_timers_are_actionnable(true);
});

$(window).scroll(function() {
	ws_timedblock.main.check_timers_are_actionnable(false);
});

$(window).resize(function() {
	ws_timedblock.main.check_timers_are_actionnable(false);
});





