/*
 * Atostogoskaime calendar grabber
 * pi@homedir.eu
 */
var gr_offset = 0
function gr_url(offset){
	date = new Date()
	year = date.getFullYear()
	month = date.getMonth() + 1;
	year += parseInt((month+offset)/12)
	month = (month + offset) % 12
	return "http://www.vidusodyba.lt/wp-content/themes/vs/proxy.php?year="+year+"&month="+month
}
function grabber(offset){
	jQuery.ajax({
		url: gr_url(offset),
		type: 'GET',
		dataType: 'text',
		async: true,
		timeout: 10000,
	    success: gr_parse
	});
}
function gr_render(data){
	html = "<strong>" + data[0]['caption'] + "</strong>"
	html += "<ul>"
	for (i = 0; i < data.length; i++){
 		html += "<li class=" + data[i]['class'] + ">"+data[i]['text']+"</li>"
	}
	html += "</ul>"
	if (gr_offset > 0){
		html += "<a class='atgal' href='javascript:gr_prev()'><span>Atgal</span></a>"
	}
	html += "<a class='dar' href='javascript:gr_next()'><span>Toliau</span></a>"	
	html += '<div class="clear"><div class="uzimta-box"><span></span>Užimta</div>'
	html += '<div class="dalinai-box"><span></span>Dalinai užimta</div></div>'
	gr_set_content(html)
	}
function gr_set_content(html){
	jQuery("#uzimtumas")[0].innerHTML = html
}
function gr_next(){
	grabber(++gr_offset)
}
function gr_prev(){
	grabber(--gr_offset)
}
function gr_parse(data){
	caption = jQuery("table > caption", data).text()
	res = new Array()
	count = 0
	first = 1
	jQuery("table > tbody > tr", data).each(function(){
		for (var i = 0; i < this.cells.length; i++){
	    	cell = this.cells[i].innerText;
			if (cell == undefined){//ff
				cell = this.cells[i].textContent;
			}
			col = this.cells[i].colSpan
			for (j = 0; j<col; j++){
				day = new Array()
				day['text'] = cell
				day['caption'] = caption
				if (first){
					day['class'] = 'title'
				} else {
					day['class'] = ''
				}
				try{
					els = jQuery("[class]", this.cells[i].innerHTML)
					if (els.length > 0){
						cls = els[0].className
						if (cls.search(/.*daylook2.*/g) != -1){
							day['class'] = 'uzimta'
						} else if (cls.search(/.*daylook1.*/g) != -1){
							day['class'] = 'dalinai'
						}
					}
				}catch(err){}			
				res[count++] = day
			}
		}
		first = 0
	})
	gr_render(res)
}


