function str_repeat(i, m) { for (var o = []; m > 0; o[--m] = i); return(o.join('')); }

function sprintf() {
	var i = 0, f = arguments[i++], o = [], m, a, p;
	while (f) {
		if (m = /^[^\x25]+/.exec(f)) o.push(m[0]);
		else if (m = /^\x25{2}/.exec(f)) o.push('%');
		else if (m = /^\x25(\+)?(0|'[^$])?(-)?(\d+)?(\.\d+)?([b-fosuxX])/.exec(f)) {
			if ((a = arguments[i++]) === false) throw("Too few arguments.");
			if (/[^s]/.test(m[6]) && (typeof(a) != 'number'))
				throw("Expecting number but found " + typeof(a));
			switch (m[6]) {
				case 'b': a = a.toString(2); break;
				case 'c': a = String.fromCharCode(a); break;
				case 'd': a = parseInt(a); break;
				case 'e': a = m[5] ? a.toExponential(m[5].charAt(1)) : a.toExponential(); break;
				case 'f': a = m[5] ? parseFloat(a).toFixed(m[5].charAt(1)) : parseFloat(a); break;
				case 'o': a = a.toString(8); break;
				case 's': a = ((a = String(a)) && m[5] ? a.substring(0, m[5].charAt(1)) : a); break;
				case 'u': a = Math.abs(a); break;
				case 'x': a = a.toString(16); break;
				case 'X': a = a.toString(16).toUpperCase(); break;
			}
			a = (/[def]/.test(m[6]) && m[1] && a > 0 ? '+' + a : a);
			p = m[4] ? str_repeat(m[2] ? m[2] == '0' ? '0' : m[2].charAt(1) : ' ', m[5] ? m[4] - String(a).length : m[4]) : '';
			o.push(m[3] ? a + p : p + a);
		} else throw("Huh ?");
		f = f.substring(m[0].length);
	}
	return(o.join(''));
}

function getElementsByClassName(oElm, strTagName, strClassName){
var arrElements = (strTagName == "*" && document.all)? document.all : oElm.getElementsByTagName(strTagName);
	    var arrReturnElements = new Array();
	    strClassName = strClassName.replace(/\-/g, "\\-");
	    var oRegExp = new RegExp("(^|\\s)" + strClassName + "(\\s|$)");
	    var oElement;
	    for(var i=0; i<arrElements.length; i++){
	        oElement = arrElements[i];
	        if(oRegExp.test(oElement.className)){
	            arrReturnElements.push(oElement);
	        }
	    }
	    return (arrReturnElements)
	}

var GR = {
	
	domain : 'http://www.guestreviewer.com/',
	app: 'http://www.guestreviewer.com/index.php/',
	
	//domain : 'http://guestreviewer.mapsack.com/',
	//app: 'http://guestreviewer.mapsack.com/index.php/',
	
	//domain: 'http://localhost/',
	//app : 'http://localhost/index.php/',
	onload : null,
	
	containers : {
		welcome : null
	},
	
	$ : function(el)
	{
		
		return document.getElementById(el);
		
	},
	
	$ES : function(cls, base)
	{
		if (typeof base == 'undefined') base = document.body;
		
		var result = getElementsByClassName(base, '*', cls);
		
		if (result.length == 0) return false;
		
		return (result.length == 1) ? result[0] : result; 
		
	},

	
	each : function(obj, fn)
	{
		
		for (n in obj) {
			
			if (typeof obj[n] != 'function') fn(obj[n],n);
		
		}
	
	},
	
	new_element : function(type, params)
	{
		
		var el = document.createElement(type);
		
		GR.each(params, function(v, k){
		
			el[k] = v;
			
		});
		
		return el;
		
	},
	
	row_find : function(array, field, value){
		
		for (var i =0; i < array.length; i++)
		{
			
			if (array[i][field] == value) return array[i];
			
		}
		
		return null;
		
	},
	
	row_find_index : function(array, field, value){
		
		for (var i =0; i < array.length; i++)
		{
			
			if (array[i][field] == value) return i;
			
		}
		
		return null;
		
	},
	
	query_string : function(params, id)
	{
		var str = [];
		
		for(key in params)
		{
			str.push(key+'='+params[key]);
		}
		
		return '?'+str.join('&amp;')+((id) ? '#'+id : '');
		
	},
	
	init : function()
	{

		if (GR.onload != null) GR.onload(); 

		if (!GR.account)
		{
			
			GR.error('account-not-found');
			return;
			
		}

		if (!GR.item_exists)	
		{
			
			if (GR.account.type == 'SINGLE')
				GR.error('hotel-not-found-single');
			else
				GR.error('hotel-not-found-multiple');
			
			return;
			
			//if (!confirm("This hotel does not exist. Would you like to add it?")) return;;
			
			//var data = GR.add.get_page_info();		

			///var form = GR.add.insert_form(data);

			//form.submit();
			
		}
			
		GR.containers.welcome = GR.$('gr_welcome_message');
		
		if (GR.item_exists == false)
		{
			dbug('Item does not exist');
			return;
		}
		
		for (var i=0; i<GR.plugins.length;i++)
		{
			if (GR.plugins[i].check()) GR.plugins[i].init();
		}
		
		GR.display_user_info();
				
	},
	
	logged_in : function()
	{
	
		return (GR.user != null);
		
	},
	
	display_user_info : function()
	{

		if (GR.containers.welcome)
		{

			if (GR.logged_in())
			{
	
				GR.containers.welcome.innerHTML = 'You are logged in as: '+GR.user.name;
			
			} else {
			
				GR.containers.welcome.innerHTML = 'You are not logged in';
			
			}
		
		}
		
		if (!GR.logged_in()) return;
				
		if (!GR.system.can_edit) return;
		
		var div = GR.new_element('div');
		div.style.position = 'absolute';
		div.style.backgroundColor = '#333';
		div.style.color = 'white';
		div.style.top = '0px';
		div.style.right = '0px';
		div.style.padding = "4px";
		div.style.fontSize = '12px';
		div.style.fontFamily = 'sans-serif';
		
		div.innerHTML = '<img src="'+GR.domain+'images/icons/png/page_key.png" style="vertical-align: middle;" /> <a style="color: #acf;" href="'+GR.app+'hotel/show/'+GR.data.hotel['hotel_id']+'">Edit this hotel</a>';
		
		document.body.appendChild(div);
	},
	
	errors : {
		'account-not-found' : 'ERROR: Guestreviewer is not correctly installed. The account you specified could not be found. Please check your gr_account variable.',
		'hotel-not-found-multiple' : 'ERROR: The hotel you specified does not exist. Please check your gr_ref_id field.',
		'hotel-not-found-single' : 'ERROR: You have not set up your hotel details yet. Plase go to the guestreviewer.com admin interface and create your hotel.'
	},
	
	error : function(code)
	{
		if (GR.errors[code]) code = GR.errors[code]; 
		alert(code);
	},
	
	add : {
		
		get_page_info : function()
		{
			
			//
			//	Check to see if title and desc data is in page.
			//
			//if (!GR.$('title')) GR.error('no-title');
			//if (!GR.$('description')) GR.error('no-desc');
			
			//
			//	Check to see exactly one .adr block appears
			//
			var adrs = GR.$ES('adr');
			//if (!adrs) GR.error('no-address');
			if ((typeof adrs == 'array')) GR.error('many-address');
			
			//
			//	Get the data from the page.
			//
			var data = {};
			
			data.title = GR.$('title') ? GR.$('title').innerHTML : null;
			data.body = GR.$('description') ? GR.$('description').innerHTML : null;
			
			data.address_street = (adrs && GR.$ES('street-address', adrs)) ? GR.$ES('street-address', adrs).innerHTML : null;
			data.address_city = (adrs && GR.$ES('locality', adrs)) ? GR.$ES('locality', adrs).innerHTML : null;
			data.address_country = (adrs && GR.$ES('country-name', adrs)) ? GR.$ES('country-name', adrs).innerHTML : null;
			data.address_zip = (adrs && GR.$ES('postal-code', adrs)) ? GR.$ES('postal-code', adrs).innerHTML : null;
			
			data.account_id = GR.account.account_id;
			data.source_id = gr_ref_id;
			data.url = window.location.href;
			
			return data;
			
		},
		
		insert_form : function(data)
		{
			
			var form = GR.new_element('form');
			form.method = "post";
			form.action = GR.app+"interface/hotelinterface/check/"+GR.account.account_id;
			
			for (key in data)
			{
				var tb = GR.new_element('textarea');
				tb.name = key;
				tb.value = data[key];
				form.appendChild(tb);
				
			}
			
			document.body.appendChild(form);
			
			return form;
			
		}
		
	},
	
	window_size : function(){
		var w = 0;
		var h = 0;

		//IE
		if(!window.innerWidth)
		{
			//strict mode
			if(!(document.documentElement.clientWidth == 0))
			{
				w = document.documentElement.clientWidth;
				h = document.documentElement.clientHeight;
			}
			//quirks mode
			else
			{
				w = document.body.clientWidth;
				h = document.body.clientHeight;
			}
		}
		//w3c
		else
		{
			w = window.innerWidth;
			h = window.innerHeight;
		}
		return {w:w,h:h};
	},
	
	window_offset : function()
	{
		var offsetX = 0;
		var offsetY = 0;

		//IE
		if(!window.pageYOffset)
		{
			//strict mode
			if(!(document.documentElement.scrollTop == 0))
			{
				offsetY = document.documentElement.scrollTop;
				offsetX = document.documentElement.scrollLeft;
			}
			//quirks mode
			else
			{
				offsetY = document.body.scrollTop;
				offsetX = document.body.scrollLeft;
			}
		}
		//w3c
		else
		{
			offsetX = window.pageXOffset;
			offsetY = window.pageYOffset;
		}
		
		
		return {x: offsetX, y: offsetY};
	},
	
	
	windows : {},
	
	close_popup_window : function()
	{
		GR.windows.bg.style.display = 'none';
		GR.windows.div.style.display = 'none';
		GR.windows.shadow.style.display = 'none';
	},
	
	gotoUrl : function(url)
	{
		window.location.href = url;
	},
	
	popup_window : function(url, use_bg)
	{
		
		if (typeof use_bg == 'undefined') use_bg = false;
		
		var size = GR.window_size();
		var offset = GR.window_offset();
		
		var bg = GR.new_element('div');
		bg.style.position = 'absolute';
		bg.style.top = '0px';
		bg.style.left = '0px';
		bg.style.width = '100%';//size.w+'px';
		bg.style.height = Math.max(document.body.clientHeight, size.h)+'px';
		bg.style.backgroundColor = '#333';
		bg.style.zIndex = '998';
		bg.style.opacity = '0.7';
		bg.style.padding = '0px';
		bg.onclick = GR.close_popup_window;
		GR.windows.bg = bg;

		var div = GR.new_element('div', {className : 'gr_popup_window'});
		div.style.position = 'absolute';
		div.style.top = (50+offset.y)+'px';
		div.style.left = '200px';
		div.style.width = (size.w-400)+'px';
		div.style.height = (size.h-100)+'px';
		div.style.background = '#333';
		div.style.zIndex = '1000';
		GR.windows.div = div;
		
		var div2 = GR.new_element('div');
		div2.style.position = 'absolute';
		div2.style.top = (34+offset.y)+'px';
		div2.style.left = '184px';
		div2.style.width = (size.w-368)+'px';
		div2.style.height = (size.h-68)+'px';
		div2.style.background = '#999';
		div2.style.opacity = '0.7';
		div2.style.zIndex = '999';
		GR.windows.shadow = div2;
		//div2.style.filter = 'alpha(opacity=70)';
		
		if (use_bg)
		{
			var iframe = GR.new_element('div');
			iframe.style.position = 'absolute';
			iframe.style.left = '16px';
			iframe.style.width = (size.w-432)+'px';
			iframe.style.top = '32px';
			iframe.style.height= (size.h-148)+'px';
			iframe.style.border = 'none';
			iframe.style.background = 'url('+url+') center no-repeat white';
			
			div.appendChild(iframe);
			
		} else {
		
			var iframe = GR.new_element('div');
			iframe.style.position = 'absolute';
			iframe.style.left = '16px';
			iframe.style.width = (size.w-432)+'px';
			iframe.style.top = '32px';
			iframe.style.height= (size.h-148)+'px';
			iframe.style.border = 'none';
			//iframe.style.width="100%";
			
			iframe.style.backgroundColor = '#fff';
		
			div.appendChild(iframe);
			
			var iframe2 = GR.new_element('iframe', {src: url});
			iframe2.style.width="100%";
			iframe2.style.height="100%";
			iframe2.style.border = 'none';
			iframe2.src = url;
			
			
			iframe.appendChild(iframe2);
		}


		var title = GR.new_element('div');
		title.style.position = 'absolute';
		title.style.top = '8px';
		title.style.right = '16px';
		title.style.color = 'white';
		title.innerHTML = 'close';
		title.style.cursor = 'pointer';
		title.onclick = GR.close_popup_window;
		div.appendChild(title);

		document.body.appendChild(bg);
		document.body.appendChild(div2);
		document.body.appendChild(div);
		
		
			
	}
	
};

GR.Reviews = {
	
	containers : {
		reviews : null
	},
	
	npp : 5,
	
	templates : {
		header 		: '<div id="gr_reviews_header"><div id="gr_reviews_header_addreview"><a href="'+GR.app+'add/review/%d/%d?url='+window.location.href+'">Add review</a></div>%d reviews in total. Page %d of %d. %s%s</div>',
		review 		: '<img src="%s" class="gr_reviews_review_mycon" />%s<div class="gr_reviews_review_inner"><div class="gr_reviews_review_inner_header">%s</div><div class="gr_reviews_review_inner_body">%s</div><div class="gr_reviews_review_inner_footer">Review by %s on %s</div></div',
		review_i	: '%s %s',
		rating_o 	: '<table class="gr_reviews_review_rating">%s</table>',
		rating_i 	: '<tr><td>%s </td><td><img height="12" src="'+GR.domain+'images/widgets/reviews/stars/score.%d.png"></td></tr>'
	},
	
	check : function()
	{
		return (GR.$('gr_reviews') != null)
	},
	
	init : function()
	{
		
		dbug("GR.Reviews loaded");
		
		this.containers.reviews = GR.$('gr_reviews');
		
		this.display_reviews();
		
	},
	
	display_reviews : function()
	{
		
		var pages = Math.max(Math.ceil(parseInt(GR.data.totalreviews) / GR.Reviews.npp), 1);
		var page = parseInt(GR.data.reviewpage);
		
		var prev = (page > 1) ? '<a href="'+GR.query_string({'gr_page' : page-1}, 'gr_reviews')+'">&laquo; prev</a>' : '';
		var next = (page < pages) ? ' <a href="'+GR.query_string({'gr_page' : page+1}, 'gr_reviews')+'">next &raquo;</a>' : '';
		
		
		GR.Reviews.containers.reviews.innerHTML = sprintf(	GR.Reviews.templates.header, 
															parseInt(GR.data.hotel.hotel_id), 
															parseInt(GR.account.account_id), 
															parseInt(GR.data.totalreviews),
															page,
															pages,
															prev,
															next);
		
		GR.each(GR.data.reviews, this.add_review);
		
	},
	
	add_review : function(review)
	{
				
		var div = GR.new_element('div', {'className' : 'gr_reviews_review'});
		
		var rec = (review.trip_recommend != null) ? '<p>I <strong>would'+((review.trip_recommend ==0) ? ' not': '')+'</strong> recommend it to my friends.</p>' : '';
		var rating = GR.Reviews.build_rating(review);
		
		var body = sprintf(GR.Reviews.templates.review_i, review.body_html, rec);
		
		div.innerHTML = sprintf(GR.Reviews.templates.review, GR.domain+review.mycon_tmb_url, rating, review.title, body, review.name, review.time_created);
		
		GR.Reviews.containers.reviews.appendChild(div);
		
	},
	
	build_rating : function(review)
	{
		var ratings = ['rating_overall', 'rating_value', 'rating_service', 'rating_location', 'rating_facilities', 'rating_clean', 'rating_room'];
		var rating_names = ['Overall', 'Value for money', 'Service', 'Location', 'Facilities', 'Cleanliness', 'Quality of room'];
		var ret = '';
		
		for(var i=0; i < ratings.length; i++){
			var rating = ratings[i];
			
			if (review[rating] == null) continue;
			
			ret += sprintf(GR.Reviews.templates.rating_i, rating_names[i], parseInt(review[rating]));
		}
		
		return sprintf(GR.Reviews.templates.rating_o, ret);
		
	}
	
}

GR.Photos = {
	
	containers : {
		large : null,
		thumbs : null
	},
	
	templates : {
		header 		: '<div id="gr_photos_header"><div id="gr_photos_header_addphoto"><a href="'+GR.app+'add/photo/%d/%d?url='+window.location.href+'">Add photo</a></div>%d photos in total.</div>'
	},
	
	check : function()
	{
		return (GR.$('gr_photos_thumbs') != null)
	},
	
	init : function()
	{
		
		dbug("GR.Photos loaded");
		
		this.containers.large = GR.$('gr_photos_slideshow');
		this.containers.thumbs = GR.$('gr_photos_thumbs');

		GR.Photos.add_slideshow_bar();
		
		GR.Photos.containers.thumbs.innerHTML = sprintf(	GR.Photos.templates.header, 
															parseInt(GR.data.hotel.hotel_id), 
															parseInt(GR.account.account_id),
															parseInt(GR.data.photos.length) 
														);
		
		if (GR.data.photos.length > 0)
		{
			this.set_photo(GR.data.photos[0].photo_id);
			this.display_thumbnails();
		}
		

	},
	
	add_slideshow_bar : function()
	{
	
		if (!this.containers.large) return;
		if (GR.data.photos.length == 0) return;
		
		var div = GR.new_element('div', {'id' : 'gr_photos_slideshow_bar'});
		
		this.containers.slideshow = div;
		
		this.containers.large.appendChild(div);
		
	},
	
	update_slideshow_bar : function(photo)
	{
		if (!this.containers.large) return;
		
		var index = GR.Photos.current_index+1;
		
		var prev = (index > 1) ? '<a href="#" onclick="GR.Photos.prev(); return false;">&laquo; prev</a> ' : '';
		var next = (index < GR.data.photos.length) ? ' <a href="#" onclick="GR.Photos.next(); return false;">next &raquo;</a>' : '';
		
		
		this.containers.slideshow.innerHTML = 'Photo '+index+' of '+GR.data.photos.length+' by '+photo.name+' '+prev+next;
			
	},
	
	next : function()
	{
		var photo = GR.data.photos[GR.Photos.current_index+1];
		GR.Photos.set_photo(photo.photo_id);
	},
	
	prev : function()
	{
		var photo = GR.data.photos[GR.Photos.current_index-1];
		GR.Photos.set_photo(photo.photo_id);
	},
	
	upload_clicked : function()
	{
		window.location.href = GR.app+'/add/photo/'+GR.data.hotel.hotel_id+'/'+GR.account.account_id+'/';
		//GR.popup_window(GR.app+'/add/photo/'+GR.data.hotel.hotel_id+'/'+GR.account.account_id+'/');
	},
	
	get_photo_by_id : function(photo_id)
	{
	
		return GR.row_find(GR.data.photos, 'photo_id', photo_id);
		
	},
	
	set_photo : function(photo_id)
	{
		if (!this.containers.large) return;
		
		var photo = this.get_photo_by_id(photo_id);
		var index = GR.row_find_index(GR.data.photos, 'photo_id', photo_id);

		GR.Photos.current_index = index;

		this.containers.large.style.background = 'url('+GR.domain+photo.url_med+') center no-repeat #eee';
		
		GR.Photos.update_slideshow_bar(photo);
		
	},
	
	popup_photo : function(photo_id)
	{
		var photo = this.get_photo_by_id(photo_id);
		
		GR.popup_window(GR.domain+photo.url, true);
		
	},
	
	photo_clicked : function(photo_id)
	{
		if (this.containers.large) 
		{
			this.set_photo(photo_id);
		} else {
			this.popup_photo(photo_id);
		}
	},
	
	display_thumbnails : function()
	{

		GR.each(GR.data.photos, this.add_thumbnail);
		
	},
	
	add_thumbnail : function(photo)
	{

		var img = GR.new_element('img', {'src' : GR.domain+photo.url_tmb, 'className' : 'gr_photos_thumbs_thumb'});
		img.onclick = GR.Photos.img_clicked;
		img._gr_photo_id = photo.photo_id;
		img.style.cursor = 'pointer';
		img.title = 'Click to see large version.';
		GR.Photos.containers.thumbs.appendChild(img);
		
	},
	
	img_clicked : function()
	{
		
		GR.Photos.photo_clicked(this._gr_photo_id);
		
	}
	
}

GR.Map = {
	
	containers : {
		map : null
	},
	
	check : function()
	{
		return (GR.$('gr_map') != null)
	},
	
	init : function()
	{
		dbug("GR.Map loaded");
		
		this.containers.map = GR.$('gr_map');
		
		GR.Map.insertIFrame();
		
	},
	
	insertIFrame : function()
	{
		var w = GR.Map.containers.map.offsetWidth;
		var h = GR.Map.containers.map.style.height.replace('px','');
		
		if (w == 0) w = GR.Map.containers.map.parentNode.offsetWidth;
		if (w == 0) w = GR.Map.containers.map.parentNode.parentNode.offsetWidth;
		
		//dbug(w+' '+h);
	
		var iframe = GR.new_element('iframe');
		iframe.scrolling = "no";
		iframe.src = GR.app+'interface/map/view/'+GR.data.hotel.hotel_id+'/'+GR.account.account_id+'?w='+w+'&h='+h;
		iframe.border = "0";
		iframe.style.border = "none";
		iframe.style.width = '100%';
		iframe.style.height = h+'px';
		
		GR.Map.containers.map.appendChild(iframe);
		
	}
	
}

GR.plugins = [GR.Reviews, GR.Photos, GR.Map];

if (typeof gr_account != 'undefined'){

	if (typeof gr_ref_id == 'undefined') gr_ref_id = window.location.href;

	var e_script = "</script>";
	document.write('<script type="text/javascript" src="'+GR.app+'interface/data/get/'+gr_account+'/'+gr_ref_id+'?rand='+(new Date()).getTime()+'&amp;url='+window.location.href+'">'+e_script);
	GR.onload = window.onload;
	window.onload = GR.init;

} else {
	
	alert("Error: GR not installed");

}

function dbug(m)
{
	if (!document.getElementById('debug')) return;
	
	var div = document.createElement('div');
	div.innerHTML = m;
	
	document.getElementById('debug').appendChild(div);
	
}