var relPath; // this gets set by base page
var staticResPath; // this gets set by base page
var scoresToDisplay;

jQuery.ajaxSetup({
	cache : false
});

function processPhotos() {
	$('canvas.photo').each(function(i) {
		// for (var canvas in YAHOO.util.Selector.query('canvas.photo')){
		// var nodes = YAHOO.util.Selector.query('canvas.photo');
		// for (var i=0;i<nodes.length;i++)
		// {
		// var canvas=nodes[i];

		// alert (canvas);
		var canvas = this;

		if (canvas.getContext) {

			var ctx = canvas.getContext("2d");

			var img = new Image();
			img.onload = function() {

				cw = canvas.width;
				ch = canvas.height;

				w = cw - 50;
				h = cw - 50;

				bw = 12;

				ctx.translate(w / 2 + 20, h / 2 + 20);
				ctx.rotate(-.1 + Math.random() * .2);
				// ctx.rotate(3.14/2);
				ctx.translate(-w / 2, -h / 2);

				// ctx.drawImage(img,0,0);

				// ctx.translate(20,20);

				// shadow
				ctx.translate(bw - 5, bw - 5);
				for (i = 5; i >= 0; i--) {
					c = 215 + i * 5;
					ctx.fillStyle = 'rgb(' + c + ',' + c + ',' + c + ')';
					ctx.fillRect(0, 0, w + bw + i, h + bw + i);
				}
				ctx.translate(-bw + 5, -bw + 5);

				// image and border

				ctx.translate(bw / 2, bw / 2);
				ctx.drawImage(img, 0, 0);
				ctx.translate(-bw / 2, -bw / 2);

				ctx.strokeStyle = "rgba(0,0,0,1)";
				ctx.lineWidth = bw;
				ctx.strokeRect(0, 0, w + bw, h + bw);
				ctx.strokeStyle = "rgba(255,255,255,1)";
				ctx.lineWidth = bw - 2;
				ctx.strokeRect(0, 0, w + bw, h + bw);

			}
			// get src of the img within the canvas, that is otherwise used
			// as fallback for older browser w/o canvas support

			// alert(canvas.getElements());

			// img.src = canvas.getElement('img').src;

			img.src = canvas.id;
		}
	});
}

function removeExampleText(field) {
	if (field.value.charAt(0) == '«'
			&& field.value.charAt(field.value.length - 1) == '»') {
		field.value = "";
		field.className = field.className.replace(/example/, "");
	}
}

function processDynamicTextAreas() {
	$('textarea.dynamicHeight').each(function(ta) {
		// for (var ta in YAHOO.util.Selector.query('textarea.dynamicHeight')){

		var origRows = ta.rows;
		ta.onfocus = function() {
			removeExampleText(ta);
			ta.rows = 15;
		};
		// ta.onblur=function(){ta.rows=origRows;};
	});
}

function showNotificationTab(text) {
	document.getElementById("notificationTabText").innerText = text;
	document.getElementById("notificationTab").style.display = '';
}

function hideFeedbackMessage() {
	document.getElementById("feedbackMessage").style.display = 'none';
}

function createXMLHttpReqObj() {
	var xmlHttp = null;
	// Mozilla, Opera, Safari sowie Internet Explorer 7
	if (typeof XMLHttpRequest != 'undefined') {
		xmlHttp = new XMLHttpRequest();
	}
	if (!xmlHttp) {
		// Internet Explorer 6 und älter
		try {
			xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try {
				xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e) {
				xmlHttp = null;
			}
		}
	}
	return xmlHttp;
}

function showHelp_internal(url, topic) {
	jQuery.modal('<div id="helpPopUp">', {
		closeHTML : "",
		containerCss : {
			backgroundColor : "#900",
			borderColor : "#000",
			height : 430,
			padding : 0,
			width : 850,
			XXoverflow : "auto"
		},
		overlayClose : true
	});

	jQuery.ajax({
		url : url,
		data : "popUp=true&topic=" + topic,
		async : true,
		success : function(data, status) {
			$("#helpPopUp").html(data);
		}
	});
}

function addScoreDisplay(userB, type) {
	if (scoresToDisplay == null)
		scoresToDisplay = new Array();
	// scoresToDisplay.push(userA+'-'+userB);
	scoresToDisplay.push({
		user : userB,
		type : type
	});
}

function getAndDisplayScores() {
	if (scoresToDisplay) {
		var ids = new Array();
		jQuery.each(scoresToDisplay, function(idx, v) {
			ids.push(v.user)
		});
		jQuery
				.get(
						relPath + '/user/questions/questionsActions.htm',
						{
							action : "getScores",
							ids : ids.join(',')
						},
						function(data) {
							jQuery
									.each(
											data,
											function(key, value) {
												// alert(key + ': ' + value);
												// alert(jQuery('score'+key));
												var d = jQuery('div.score'
														+ key);
												if (d.hasClass('barIcon')) {
													if (value < 0)
														d.html('');
													else
														d
																.html('<div title="'
																		+ value
																		+ '%" class="scoreBarIcon" style="background-position:0 -'
																		+ Math
																				.floor(value / 10)
																		* 7
																		+ 'px"></div>');
												} else {
													d
															.removeClass('scoreThrobber');
													if (value < 0)
														d.html("---");
													else
														d.html(value + "%");
												}
											});
						}, "json");
	}
}

function detectAndSaveLocation(args) {
	// alert("Blubb");
	if (navigator.geolocation) {
		// alert("Blubb2");

		jQuery.blockUI({message: messages.locatingYouPleaseWait+'<img src="'+staticResPath+'/img/throbber_whiteOnRed.gif" style="display:block;margin:0 auto;margin-top:2em">',css: {background:"#600",color:"#FFF",borderColor:"#900",padding:"3em",lineHeight:"1.5"}, overlayCSS: { backgroundColor: '#000' }, fadeOut: 0});

		navigator.geolocation.getCurrentPosition(function(position) {
			// alert("Blubb3");
			var display, addr;
			var geocoder = new google.maps.Geocoder();
			geocoder.geocode({
				'latLng' : new google.maps.LatLng(position.coords.latitude,
						position.coords.longitude)
			}, function(results, status) {
				if (status == google.maps.GeocoderStatus.OK) {

					/*
					 * // if there is more then one result, take the second
					 * because the first is "too" exact (street name) if
					 * (results.length>1) place = results[1]; else place =
					 * results[0];
					 *
					 * display = place.formatted_address;
					 */

					display = getBestDisplayForGeocoderResult(results);
					addr = getAddressComponents(results[0]);

					// alert(display);
				}
				// alert(status);
				// alert(relPath);

				//alert(JSON.stringify(addr));

				jQuery.get(relPath + '/user/userAction.htm', {
					action : 'setDetectedLocation',
					lon : position.coords.longitude / 180.0 * Math.PI,
					lat : position.coords.latitude / 180.0 * Math.PI,
					display : display,
					city: addr.city,
					region: addr.region,
					countryCode : addr.countryCode
				}, function(data) {
					if (args.success)
						args.success();
				});

				jQuery.unblockUI();
			});
		}, function(error) {

			jQuery.unblockUI();

			if (args.error)
				args.error(error);
		});
	} else {
		var error = new Object();
		error.code = -1;
		if (args.error)
			args.error(error);
	}
}

function getBestDisplayForGeocoderResult(results) {
	var res = getAddressComponents(results[0]);
	if (res.city != null)
		return res.city;
	if (res.region != null)
		return res.region;
	if (res.country != null)
		return res.country;
	return "?";
}

function getAddressComponents(place) {
	var res = new Object();

	jQuery.each(place.address_components,
			function(index, ac) {
				if (jQuery.inArray("country", ac.types) >= 0) {
					res.country = ac.long_name;
					res.countryCode = ac.short_name;
				} else if (!res.region
						&& jQuery.inArray("administrative_area_level_3",
								ac.types) >= 0) {
					res.region = ac.long_name;
				} else if (!res.region
						&& jQuery.inArray("administrative_area_level_2",
								ac.types) >= 0) {
					res.region = ac.long_name;
				} else if (!res.region
						&& jQuery.inArray("administrative_area_level_1",
								ac.types) >= 0) {
					res.region = ac.long_name;
				} else if (!res.region
						&& jQuery.inArray("colloquial_area", ac.types) >= 0) {
					res.region = ac.long_name;
				} else if (jQuery.inArray("locality", ac.types) >= 0) {
					res.city = ac.long_name;
				}
			});

	return res;
}

function showGeoLocationErrorMessage(error){
	switch (error.code)
	{
		case -1:
	 		alert(messages.noGeolocationBrowserSupport);
			break;
		case error.PERMISSION_DENIED:
			alert(messages.geoLocationError_permissionDenied);
			break;
		case error.POSITION_UNAVAILABLE:
		case error.TIMEOUT:
			alert(messages.geoLocationError_positionUnavailable);
			break;
		default:
	 		alert(messages.unknownGeolocationError);
	}
 }

function UrlFragment()
{
        this.param = function(s,v)
                {
                        this.init();
                        if (v === undefined)
                                return this.params[s];
                        else
                                this.params[s]=v;
                };

        this.removeParam = function(s)
                {
                        this.init();
                        this.params[s]=undefined;
                };

        this.init = function()
        {
                if (typeof(this.params) === 'undefined')
                {
                        this.params=new Object();
                        var h = window.location.hash.substring(1);
                        if (h !== undefined && h.length > 0)
                        {
                                var sp=h.split(';');
                                for (var i = 0; i < sp.length; ++i)
                                {
                                        var kv=sp[i].split('=',2);
                                        //alert(kv[0] + " => " + kv[1]);
                                        this.params[kv[0]]=kv[1];
                                }
                        }
                }
        };

        this.hash = function()
        {
                this.init();
                var hash='#';
                for (var p in this.params)
                {
                        var v=this.params[p];
                        if (v !== undefined)
                        {
                                if (hash!='#') hash+=';';
                                hash += p+"="+v;
                        }
                }
                return hash;
        };

        this.setLocationHash = function()
        {
                location.hash = this.hash();
        };
};
var urlFragment=new UrlFragment();


function dontShowAgain(idx)
{
	jQuery.post(relPath+"/user/userAction.htm", { action:"setMiscFlag", idx: idx });
	jQuery('#dontShowAgain-'+idx).fadeOut();
}
