$(document).ready(function() {

	oTools = new JunaioTools();
	oAjax = new JunaioAjax();
	oSidebar = new JunaioSidebar();
	oIndexActivity = new JunaioIndexActivity();

	// Twitter receiver
	oTwitter = new Object();
	oGeoLocate = new JunaioGeoLocate();
});

function JunaioTools() {

	this.oTwitterCallbacks = {};

	this.init = function() {
		var that = this;
		// Attach submit events
		$('.submitlink').click(function() { return that.submit(this); });
		
		// Attach menu hover effects
		$('a.menu').mouseover(function() { that.menuover(this); });
		$('a.menu').mouseout(function() { that.menuout(this); });
	};

	this.setCookie = function(sKey, sValue) {
		var oDate = new Date();
		oDate = new Date(oDate.getTime() +1000*60*60*24*365);
		document.cookie = sKey + '=' + sValue + '; expires=' + oDate.toGMTString() + '; path=/';
	};

	this.getTwitter = function(sId, sUsername, oCallback) {
		var that = this;
		var jTwitter = new JunaioTwitter(oCallback);
		oTwitter[sId] = jTwitter;
		var script = document.createElement('script');
		script.setAttribute('src', 'http://search.twitter.com/search.json?g=&from=' + sUsername + '&rpp=1&callback=oTwitter.' + sId + '.receiveTwitter');
		$('head').append(script);
	};

	this.submit = function(oElement) {
		$(oElement).closest('form').submit();
		return false;
	};

	this.menuover = function(oElement) {
		/*var aClasses = $(oElement).attr('class').split(' ');
		for (var i=0; i<aClasses.length; i++) {
			if (aClasses[i] != 'menu' && aClasses[i] != 'hidden') {
				var sCurrentClass = aClasses[i];
				$(oElement).removeClass(sCurrentClass);
				$(oElement).addClass(sCurrentClass + '-on');
				return true;
			}
		}*/
	};

	this.menuout = function(oElement) {
		/*var aClasses = $(oElement).attr('class').split(' ');
		for (var i=0; i<aClasses.length; i++) {
			if (aClasses[i] != 'menu' && aClasses[i] != 'hidden') {
				var sCurrentClass = aClasses[i];
				$(oElement).removeClass(sCurrentClass);
				$(oElement).addClass(sCurrentClass.substr(0,sCurrentClass.length-3));
				return true;
			}
		}*/
	};

	this.popup = function(sUrl, sTitle) {
		window.open(
			sUrl,
			sTitle,
			'screenX=100, screenY=100, height=550px, width=650px, scrollbars=yes'
		);
	};
	
	this.cutString = function(string, length)
	{
		if(string.length > length)
			return(string.substring(0, length) + "...");
		else
			return(string);		
	};
	
	this.linkTwitter = function(text) {
		
		var twitterer = new RegExp(/(@+\w*(\s|,|!|\.|\n))/);
		var url = new RegExp(/[^"|^>](http:\/\/+[\S]*)/);  
		
		while(twitterer.exec (text) != null) {  
			text = text.replace(twitterer, this.twittererNameLink);  
		}  

		while(url.exec (text) != null) {  
			text = text.replace(url, this.twitterURLLink);  
		} 
		
		return text;		
	};
	
	this.twitterURLLink = function() {  
		return " <a href=\""+arguments[1]+"\" target=\"_blank\">"+arguments[1]+"</a>";  
	};
	
	this.twittererNameLink = function(){  
		return " <a href=\"http://twitter.com/"+arguments[1].substr(1,arguments[1].length-2)+"\" target=\"_blank\">@"+arguments[1].substr(1,arguments[1].length-2)+"</a>"+arguments[1].substr(arguments[1].length-1,1);  
	};
	
	this.init();

};

function JunaioAjax() {

	this.iAjaxInProgress = {};
	this.oAjaxCallback = {};
	this.oAjaxStack = {};
	
	this.init = function() {
		var that = this;
		//$(document).ajaxError(function(e, r, o, t) { that.error(e, r, o, t); });
		$.ajaxSetup({timeout: 20000});
	};

	this.stacksend = function(sType, sMethod, sUrl, oParams, oCallback) {
		var oDate = new Date();
		if (this.iAjaxInProgress[sType] != null && this.iAjaxInProgress[sType] - oDate.getTime() < 20000) {
			this.oAjaxStack[sType] = {sMethod: sMethod, sUrl: sUrl, oParams: oParams, oCallback: oCallback};
		} else {
			var that = this;
			this.iAjaxInProgress[sType] = oDate.getTime();
			if (sMethod == 'get') {
				oAjax.get(sUrl, oParams, function(oData) { that.stackreceive(sType, oData); });
			} else {
				oAjax.post(sUrl, oParams, function(oData) { that.stackreceive(sType, oData); });
			}
			this.oAjaxCallback[sType] = oCallback;
			this.oAjaxStack[sType] = null;
		}
	};

	this.stackreceive = function(sType, oData) {
		this.oAjaxCallback[sType](oData);
		this.oAjaxCallback[sType] = null;
		this.iAjaxInProgress[sType] = null;
		if (this.oAjaxStack[sType] != null) {
			this.stacksend(
					sType,
					this.oAjaxStack[sType].sMethod,
					this.oAjaxStack[sType].sUrl,
					this.oAjaxStack[sType].oParams,
					this.oAjaxStack[sType].oCallback
			);
			this.oAjaxStack[sType] = null;
		}
	};

	this.get = function(sUrl, aParams, oCallback) {
		var that = this;
		$.getJSON(sUrl, aParams, function(oResponse) { that.receive(oResponse, oCallback); });
	};

	this.post = function(sUrl, aParams, oCallback) {
		var that = this;
		$.ajaxSetup({timeout: 20000, async: false});
		$.post(sUrl, aParams, function(oResponse) {$.ajaxSetup({timeout: 20000, async: true}); that.receive(oResponse, oCallback); }, 'json');
	};

	this.receive = function(oResponse, oCallback) {
		var that = this;
		if (oResponse.iCode == 401) {
			this.login();
		} else if (oResponse.iCode == 200) {
			$('#sidebarLoader').css({visibility:"hidden"});
			oCallback(oResponse.mData);
		} else if (oResponse.iCode == 201) {
			$('#sidebarLoader').css({visibility:"hidden"});
			$.modaldialog.warning(oResponse.mData, {width: 300});
		} else if (oResponse.iCode == 302) {
			$('#sidebarLoader').css({visibility:"hidden"});
			$.modaldialog.success(oResponse.mData.message, {width: 300, callback: function() {that.redirect(oResponse.mData.url); }});
		} else {
			this.error();
		}
	};

	this.redirect = function(sUrl) {
		window.setTimeout(function() { location.href = sUrl; }, 2000);
	};

	this.error = function(e, r, o, t) {
		$.modaldialog.error(oJunaioTranslate.getTranslation('ajaxerror'), {width: 300, timeout: 5});
	};

	this.login = function() {
		$.modaldialog.warning(oJunaioTranslate.getTranslation('ajaxunauthorized'), {width: 300});
	};

	this.fakejax = function(oForm, sUrl, oCallback) {
		if ($.browser.msie) {
			$('#fakejax').unbind('ready');
			$('#fakejax').ready( function() { oCallback(); return false; });
		} else {
			$('#fakejax').unbind('load');
			$('#fakejax').load( function() { oCallback(); return false; });
		}
		$(oForm).attr('action', sUrl);
		$(oForm).attr('target', 'fakejax');
		$(oForm).submit();
	};

	this.init();

};

function JunaioTranslate() {

	var oStrings = {};

	this.addTranslation = function(sKey, sString) {
		oStrings[sKey] = sString;
	};

	this.getTranslation = function(sKey) {
		if(oStrings[sKey] == null) {
			return '-' + sKey + '-';
		}
		return oStrings[sKey];
	};

};

function JunaioIndexActivity() {
	
	var that = this;
	var cnt = 0;
	
	this.geoAnimate = function(sSnippet, oInitCallback, sIndex) {
		$('#indexNewestContent').fadeOut('fast', function() { that.geoReplaceShow(sSnippet, oInitCallback, sIndex); });
	};

	this.geoReplaceShow = function(sSnippet, oInitCallback, sIndex) {
		$('#indexNewestContent').html(sSnippet).fadeIn('slow', function() { if (oInitCallback != undefined) { oInitCallback(); } });
		
		/*for(var i = 0; i < $('#indexNewestContent .news').length; i++)
			this.getAddress($('#indexNewestContent .news .lat:eq(i)').html(),$('#indexNewestContent .news .lon:eq(i)').html());*/
		
		cnt = 0;
		
		jQuery.each($('#indexNewestContent .news'), function(){
			//avoid blocking of google Mpas access
			oGeoLocate.getAddress($(this).children('.lat').html(),$(this).children('.lon').html(), that.addressCallback);
		});
	};
	
	this.addressCallback = function(address)
	{
		var div = $('#indexNewestContent .news .location')[cnt];
		div.innerHTML = address;
		
		cnt++;		
	};

};

function JunaioSidebar() {

	this.current = null;
	this.history = null;
	this.begin = null;
	this.stack = {};
	
	var that = this;
	
	//needed for geo replacing (Interval needs to be set up, or Google will return 602 - too fast following requests
	this.iCntMap = 0;
	this.iLastCntMap = -1;
	this.iIntervalID = 0;

	this.init = function(oInitCallback, oUninitCallback, sIndex) {
		this.current = {sSnippet: $('#sidebar').html(), oInitCallback: oInitCallback, oUninitCallback: oUninitCallback, sIndex: sIndex};
		this.history = this.current;
		this.begin = this.current;
		this.stack[sIndex] = this.current;
	};

	this.animate = function(sSnippet, bStack, oInitCallback, oUninitCallback, sIndex) {
		var that = this;
		$('#sidebarLoader').css({visibility:"visible"});
		if (this.current.oUninitCallback != undefined) {
			this.current.oUninitCallback();
		}
		$('#sidebar').fadeOut('fast', function() { that.show(sSnippet, bStack, oInitCallback, oUninitCallback, sIndex); });
	};

	this.show = function(sSnippet, bStack, oInitCallback, oUninitCallback, sIndex) {
		if (bStack == true) {
			if (this.current != null) {
				this.history = this.current;
			}
		}
		this.current = {sSnippet: sSnippet, oInitCallback: oInitCallback, oUninitCallback: oUninitCallback};
		this.stack[sIndex] = this.current;
		$('#sidebar').html(sSnippet).fadeIn('fast', function() { if (oInitCallback != undefined) { oInitCallback(); } });
		
		$('#sidebarLoader').css({visibility:"hidden"});		
	};

	this.back = function() {
		if (this.history != null) {
			this.animate(this.history.sSnippet, false, this.history.oInitCallback, this.history.oUninitCallback, this.history.sIndex);
		}
	};

	this.restart = function() {
		if (this.begin != null) {
			this.animate(this.begin.sSnippet, false, this.begin.oInitCallback, this.begin.oUninitCallback, this.begin.sIndex);
		}
	};

	this.load = function(sIndex) {
		if (this.stack[sIndex] != undefined) {
			this.animate(this.stack[sIndex].sSnippet, false, this.stack[sIndex].oInitCallback, this.stack[sIndex].oUninitCallback, sIndex);
		}
	};

	this.change = function(sIndex, sSnippet) {
		if (this.stack[sIndex] != undefined) {
			this.stack[sIndex].sSnippet = sSnippet;
		}
		if (this.current.sIndex == sIndex) {
			this.current.sSnippet = sSnippet;
		}
		if (this.history.sIndex == sIndex) {
			this.history.sSnippet = sSnippet;
		}
		if (this.begin.sIndex == sIndex) {
			this.begin.sSnippet = sSnippet;
		}
	};

	this.getAddresses = function() {
		clearInterval(this.iIntervalID);
		this.iCntMap = 0;
		this.iLastCntMap = -1;
		this.iIntervalID = setInterval("oSidebar.fetchNewsAdress()", 100);
	};
	
	this.fetchNewsAdress = function(){
		if(this.iLastCntMap != this.iCntMap)
		{
			if($('#sidebar .news').length <= this.iCntMap)
				clearInterval(this.iIntervalID);
			else
			{
				this.iLastCntMap = this.iCntMap;
				
				var dummyLat = $('#sidebar .news .lat')[this.iCntMap];
				var dummyLng = $('#sidebar .news .lng')[this.iCntMap];
				
				oGeoLocate.getAddress(dummyLat.innerHTML, dummyLng.innerHTML, that.showNewsAdress);			
			}
		}
	}; 	
	
	this.showNewsAdress = function(address)
	{
		var div = $('#sidebar .news .location .locationInside')[that.iCntMap];
		try{
			div.innerHTML = address;
		}
		catch(e){
			clearInterval(this.iIntervalID);
		}
		
		that.iCntMap++;
	};
};

function JunaioTwitter(oCallback) {

	this.oCallback = oCallback;

	this.receiveTwitter = function(oData) {
		if (oData.results[0] != undefined) {
			this.oCallback(oData.results[0].text);
		} else {
			this.oCallback('');
		}
	};
};

function JunaioGeoLocate() {

	var that = this;
	
	this.oGeoCallback = {};
		
	this.geocoder = new GClientGeocoder();
	
	this.getAddress = function(lat, long, callback)
	{
		var that = this;
		
		that.oGeoCallback = callback;
		
		this.geocoder.getLocations(new GLatLng(lat, long), that.returnAddress);		
	};
	
	this.returnAddress = function(response)
	{
		if(!response || response.Status.code != 200)
		{
			that.oGeoCallback("");
		}
		else
		{
			var place = response.Placemark[0];
			
			if(place.AddressDetails.Country.CountryName == undefined)
				that.oGeoCallback("");	
			else if (place.AddressDetails.Country.AdministrativeArea == undefined)
				that.oGeoCallback(place.AddressDetails.Country.CountryName);
			else if(place.AddressDetails.Country.AdministrativeArea.Locality == undefined)
				that.oGeoCallback(place.AddressDetails.Country.AdministrativeArea.AdministrativeAreaName + ", "+ place.AddressDetails.Country.CountryName);
			else
				that.oGeoCallback(place.AddressDetails.Country.AdministrativeArea.Locality.LocalityName + ", "+ place.AddressDetails.Country.CountryName);
				
		}
	};
};

function JunaioRating() {
}
JunaioRating.rateScene = function(sTemplate, iId, oCallback) {
	JunaioRating.rate('scene', sTemplate, iId, oCallback);
};
JunaioRating.ratePlacedmodel = function(sTemplate, iId, oCallback) {
	JunaioRating.rate('placedmodel', sTemplate, iId, oCallback);
};
JunaioRating.rate = function(sType, sTemplate, iId, oCallback) {
	oAjax.post(
		'/ajax/ratings/create/',
		{ type: sType, id: iId, template: sTemplate },
		oCallback
	);
};

function JunaioComment() {
}
JunaioComment.commentScene = function(sTemplate, iId, sValue, oCallback) {
	JunaioComment.comment('scene', sTemplate, iId, sValue, oCallback);
};
JunaioComment.commentPlacedmodel = function(iId, sValue, oCallback) {
	JunaioComment.comment('placedmodel', sTemplate, iId, sValue, oCallback);
};
JunaioComment.comment = function(sType, sTemplate, iId, sValue, oCallback) {
	oAjax.post(
		'/ajax/comments/create/',
		{ type: sType, id: iId, value: sValue, template: sTemplate },
		oCallback
	);
};
