var loginVisible = false;

var map;
var muMap;

var markers = {};

var zoomSteps = [2,4,8,11];
var zoomIndex = -1;
var bounds; // the bounds of the loaded project shape
var interruptZoomChange = false;

function showLoginForm(){
	$(this).blur();
	if (!loginVisible) {
		$('#loginbox').slideDown(900);
		loginVisible = true;
	}	
	else {
		$('#loginbox').slideToggle(500);
		loginVisible = false;
	}
	
	return false;
}


$(document).ready(function(){
	$('ul.firstmenu li a').bind('click',function(){
		if (typeof temporaryNoLoginMessage != 'undefined') {
			alert(temporaryNoLoginMessage);
		}
		else {
			$('#loginbox').slideToggle(400);
		}
		this.blur();
		return false;
	});
	$('#registerLink').bind('click',climateprojects.showRegistrationForm);
	$('#feedbackLink').bind('click',climateprojects.showFeedbackForm);
	
	if(typeof google != 'undefined' && typeof initProjectMap == 'function'){
		initProjectMap();
	}
	
	

});

/** disable the password hash  */
MTExtranet_GeneratePasswordHash = function(){
	return true;
}

// Thickbox

var tb = {

	resize: function(w){
	
		//$('#TB_ajaxContent').css('backgroundColor', 'transparent');
		$('#TB_window').animate({
			marginLeft: w * (-0.5) + 'px',
			width: w + 'px'
		}, 800);
		//$('#TB_ajaxContent').css('backgroundColor', '#CCC');
		$('#TB_ajaxContent').animate({
			width: w + 'px'
		}, 800, 0, function(){
			$('#widgetEditViewContent').fadeIn('slow');
			$('#TB_ajaxContent').css('backgroundColor', 'transparent');
			$('#TB_window').trigger('resizeComplete');
			TB_WIDTH = w;
			//$('#TB_window').css('top','20px');
		});
		
	},
	show: function(){
		if (document.getElementById("TB_overlay") === null) {
			$("body").append("<div id='TB_overlay'></div><div id='TB_window'></div>");
			//$("#TB_overlay").click(tb_remove);
		}
		$("#TB_overlay").css('opacity', '0');
		$("#TB_overlay").css('backgroundColor', '#000000');
		$("#TB_overlay").animate({
			opacity: '0.6'
		}, 1000);
		$("#TB_overlay").addClass("TB_overlayBG");
	}
	
}

var widgetContents = {};

var widget = {
	getContent : function(widgetId,rating,certification){
		if (typeof projectId == 'undefined') {
			return;
		}
		else {
			if (widgetId == 'ManagementUnits' && $('#' + widgetId + 'WidgetContent').length > 0) {
				// do not reload the Management unit widget
				if ($('#' + widgetId + 'WidgetContent').html().length > 500) {
					this.getContentComplete(
						{
							widgetId : widgetId,
							width : 800,
							noReload : true
						}
					);
					return true;
				}
			}
			varObj = {
				widgetId: widgetId,
				projectId: projectId,
				_fnc: 'getWidgetContent',
				callbackFunction: 'getContentComplete'
			}
			if(typeof rating != 'undefined' && rating){
				varObj.rating = 1;
			}
			if(typeof certification != 'undefined' && parseInt(certification) > 0){
				varObj.certification = certification;
			}
			sendVars(varObj);
			return false;
		}
	}
	
	,close : function(widgetId){
		$('#' + widgetId + 'WidgetContent').hide();
		tb_remove();
	}

	,getContentComplete: function (data,success){
		
		var widgetContainer = $('#' + data.widgetId + 'WidgetContent');
		
		if(typeof data.error != 'undefined'){
			alert(data.error);
			return;
		}
		
		if(typeof data.preLoadScript != 'undefined'){
			$.getScript(data.preLoadScript);
		}
		
		if(typeof data.noReload == 'undefined'){
			// the MU widget won't be reloaded
			widgetContainer.html(data.content);
		}
		

		widgetContainer.hide();
		
		tb_show('Edit','#TB_inline?width=1&height=600&modal=true&inlineId=widgetContainer');
		
		var h = widgetContainer.height();
		
		$('#TB_ajaxContent').height(h+20);
		
		topVal = parseInt(($(window).height()-h)/2);
	
		if(topVal < 0){
			$('#TB_window').css('position','absolute');
			$('#TB_window').css('margin-top','0px');
			$('#TB_window').css('top','5px');
			
		}
		else {
			$('#TB_window').css('margin-top',0);
		
			$('#TB_window').css('top',topVal + 'px');
		}
						
		if(typeof data.width != 'undefined'){
			w = data.width;
		}
		else if (typeof widgetContainer.width() != 'undefined' ){
			w = widgetContainer.width();
		}
		else w = 700;
		
		tb.resize(w);
		
		$('#TB_window').one('resizeComplete',function(){
				widgetContainer.fadeIn('slow');
		})
		
		$('.closeButton').bind('click',function(){
			if($('#editDocumentsContent:visible').length < 1){
				tb_remove();
				return false;
			}
		});
		
		if(typeof data.js != 'undefined'){
			eval(data.js);
		}
	}

}



var climateprojects = {
	registrationUrl : 'http://' + window.location.host + '/Hidden/Register.html'
	,registrationMailValid : false
	,currentFeedback : 0
	,feedbackChanged : false
	,getLocalizedTextFields: function(projectId,language,linkObj){
		linkObj.blur();
		$('.activeFlag').removeClass('activeFlag');
		$(linkObj).addClass('activeFlag');
		sendVars({
			projectId: projectId
			,language:language
			,_fnc:'getLocalizedText'
			,callbackFunction : 'getLocalizedTextFieldsComplete'
		
		});
		return false;
	}
	
	,getLocalizedTextFieldsComplete : function(data,status){
		if (status == 'success') {
			
			if (typeof data.fields != 'undefined') {
				for (key in data.fields) {
					$('#project_' + key).html(data.fields[key]);
				}
			}
		}
	}
	,showRegistrationForm : function(){
		$('#loginbox').slideToggle(0);
		loginVisible = false;
		tb.show();
		this.registrationFormComplete = false;
		if($('#registrationFormWrapper').length < 1){
			
			registrationForm = '<div id="registrationFormWrapper" class="round"><form >';
			registrationForm += '<div style="float:right;width:20px;cursor:pointer;margin:4px 4px 8px ;"><img src="/img/icons/functions/close.png" id="registrationCloseButton" /></div><h3>Sign up</h3>';
			registrationForm += '<div class="inputRow"><label>Firstname:</label><input id="registrationFirstname" class="round" type="input" value="" name="firstname"/></div>';
			registrationForm += '<div class="inputRow"><label>Name:</label><input id="registrationName" type="text" value=""  class="round"  name="name"/></div>';
			registrationForm += '<div class="inputRow"><label>Email:</label><input  id="registrationMail" type="text" value=""  class="round" name="email"/></div>';
			//registrationForm += '<p>By clicking <strong>Create account</strong> you agree to the <a onclick="return OpenPopupWindow(\'/General-Terms-and-Conditions.html\',\'Terms of Service\',500,600,true)" href="/General-Terms-and-Conditions.html" target="_blank" >Terms of Service</a> and the <a onclick="return OpenPopupWindow(\'/Privacy_and_Security_Policy.html\',\'Terms of Service\',500,600,true)" href="/Privacy_and_Security_Policy.html" target="_blank" >Privacy Policy</a><br />';
			registrationForm += '<p>' + getLL('signupAcceptAGB');
			registrationForm += '<button class="button grey" id="registrationSubmitButton"> Create my account </button></p>';
			registrationForm += '<p>' + getLL('signupPopupText') + '</p>';
			//registrationForm += '<p>Your one-year free trial lasts until ' + dateParts[2]  + '. ' + dateParts[1] + '. ' +  (d.getFullYear() +1) + '. Your project account will automatically be closed, if you do not want to continue usinf ClimateProjects. .... </p>';
			registrationForm += '</form></div>';
			$('body').append(registrationForm);
			d = new Date();
			dateParts = d.toString().split(' ');
			$('#signupdate').text(dateParts[2]  + '. ' + dateParts[1] + '. ' +  (d.getFullYear() +1));
			$('#registrationCloseButton').bind('click',function(){
				climateprojects.closeRegistrationForm();
			});
			$('#registrationFirstname').bind('keyup',function(){
				climateprojects.validateRegistrationForm();
				return false;
			});
			$('#registrationName').bind('keyup',function(){
				climateprojects.validateRegistrationForm();
				return false;
			});
			$('#registrationMail').bind('keyup',function(){
				if(climateprojects.validateEmail(this.value)){
					climateprojects.checkUnique( $(this).val(),climateprojects.registrationUrl);
				}
				return false;
			});
			$('#registrationSubmitButton').bind('click',function(){
				
				if(climateprojects.validateRegistrationForm(true)){
					sendVars({
					    'module_fnc[spota]':'PostData'
						,'dataType' : 'html'
					    ,'aInput[firstname]':$('#registrationFirstname').val()
					    ,'aInput[lastname]':$('#registrationName').val()
						,'aInput[email]':$('#registrationMail').val()
						,callbackFunction:'registrationComplete'
					    },
					    climateprojects.registrationUrl
					);
					
					return false;
				}
				return false;
			});
			
		}
		else $('#registrationFormWrapper').show();
		$('#registrationFormWrapper').css('top',parseInt(($(window).height()-300)/2) + 'px');
		$('#registrationFormWrapper').css('left',parseInt(($(window).width()-280)/2) + 'px');
		
		return false;
	}
	
	,validateRegistrationForm : function(finalValidation){
		if(typeof finalValidation == 'undefined')finalValidation = false;
		valid = true;
		if ($('#registrationFirstname').val().length < 3){
			if(finalValidation)climateprojects.markErrorField('registrationFirstname','Please enter at least 3 characters');
			valid = false;
		} 
		else climateprojects.removeError('registrationFirstname');
		if($('#registrationName').val().length < 3){
			if(finalValidation)climateprojects.markErrorField('registrationName','Please enter at least 3 characters');
			valid = false;
		}
		else climateprojects.removeError('registrationName');
		if($('#registrationMail').val().length < 3){
			if(finalValidation)climateprojects.markErrorField('registrationMail','Please enter valid mail adress');
			valid = false;
		}
		else if(valid && !climateprojects.registrationMailValid) {
			valid = false;
			$('#registrationSubmitButton').addClass('grey');
			if(climateprojects.validateEmail($('#registrationMail').val())){
				if(finalValidation)climateprojects.checkUnique($('#registrationMail').val(),climateprojects.registrationUrl);
			}
		}
		else climateprojects.removeError('registrationMail');
		if(valid)$('#registrationSubmitButton').removeClass('grey');
		return valid;
	}
	
	,registrationComplete : function(html,status){
		r = $(html).find('#accountCreatedMessage').html();
		$successMessage = r;
		$successMessage += '<button class="button" onclick="climateprojects.closeRegistrationForm();">Close</button>'
		$('#registrationFormWrapper').html($successMessage);
		$('#registrationFormWrapper').css('text-align','center');
		$('#registrationFormWrapper div').css('padding','0 10px');
	}
	
	,closeRegistrationForm: function(){
		$('#registrationFormWrapper').remove();
		tb_remove();
		return false;
	}
	
	,checkUnique : function(value,url){
		$('#ajax-loader-email').remove();
		$('#registrationMail').after('<img src="/img/small-ajax-loader.gif" alt="Checking for uniqueness" id="ajax-loader-email" class="inputValidationIcon"/>');
		sendVars({
			'module_fnc[spota]':'ExecuteAjaxCall'
			,value : value
			,dataType : 'json'
			,_fnc:'checkUniqueMail'
			,callbackFunction : 'checkUniqueComplete'
		},url);
		
	}
	
	,checkUniqueComplete : function(data){
		if(typeof data.unique != 'undefined'){
			if (data.unique) {
				$('#ajax-loader-email').attr('src', "/img/icons/functions/accepted.png");
				climateprojects.registrationMailValid = true;
				
			}
			else {
				$('#ajax-loader-email').attr('src', "/img/icons/functions/alert.png");
				climateprojects.markErrorField('registrationMail','This mail adress is already registered!');
			}
		}
		else {
			if(typeof data.error != 'undefined'){
				$('#ajax-loader-email').attr('src', "/img/icons/functions/alert.png");
				climateprojects.markErrorField('registrationMail','Mail not valid!');
				
			}
		}
		climateprojects.validateRegistrationForm();
	}
	
	,markErrorField : function (fieldId,error){
		$('#' + fieldId).attr('title',error);
		$('#' + fieldId).wTooltip();
		$('#' + fieldId).addClass('error');
	}
	
	,removeError:function(fieldId){
		$('#' + fieldId).removeClass('error');
		$('#' + fieldId).attr('title','');
	}
	
	,bindUniqueCheck : function(field,fieldId){
			
		$('#' + fieldId).bind('blur', function(){
			if (this.value != '') {
				$('#ajax-loader-' + field).remove();
				$(this).after('<img src="/img/small-ajax-loader.gif" alt="Checking for uniqueness" id="ajax-loader-email" class="inputValidationIcon"/>');
				climateprojects.checkUnique(table, field, $(this).val());
			}
		});
	}
	
	
	
	,showFeedbackForm : function(){
		tb.show();
		climateprojects.currentFeedback = 1; // default
		if ($('#feedbackFormWrapper').length < 1) {
			feedbackForm = '<div id="feedbackFormWrapper" class="round"><form >';
			feedbackForm += '<div style="float:right;width:20px;cursor:pointer;margin:4px;"><img src="/img/icons/functions/close.png" id="feedbackCloseButton" /></div><h3>Feedback</h3>';
			//feedbackForm += '<input type="hidden" value="Login" name="module_fnc[login]"/>';
			feedbackForm += '<div class="inputRow" id="feedbackLinks">';
			feedbackForm += '<span><a href="#"><img class="checkedFeedback"  id="Link1" src="/img/icons/feedback/feedback_question_.png" alt="Describe your question..." /></a></span>';
			feedbackForm += '<span><a href="#"><img  id="Link2" src="/img/icons/feedback/feedback_missing.png" alt="Describe the missing feature..." /></a></span>';
			feedbackForm += '<span><a href="#" ><img id="Link3" src="/img/icons/feedback/feedback_idea.png" alt="Describe your Idea..." /></a></span>';
			feedbackForm += '<span><a href="#" ><img  id="Link4" src="/img/icons/feedback/feedback_error.png" alt="Describe the error..." /></a></span>';
			feedbackForm += '</div>';
			feedbackForm += '<div class="inputRow"><textarea class="round" id="feedbackText"></textarea></div>';
			feedbackForm += '<div class="inputRow"><label>Email (optional):</label> <input style="border:1px solid #CCCCCC" type="text" size="40" class="round" id="emailField"/><br/><br/></div>';
			feedbackForm += '<button class="button grey" id="feedbackSubmitButton">Send</button>';
			feedbackForm += '</form></div>';
			$('body').append(feedbackForm);
			$('#feedbackCloseButton').bind('click',climateprojects.closeFeedbackForm);
			$('#feedbackLinks img').bind('click',function(){
				$(this).parent().blur();
				if($(this).hasClass('checkedFeedback'))return false;
				$('.checkedFeedback').each(function(){
					this.src = this.src.replace('_.png','.png');
					$(this).removeClass('checkedFeedback');
				});
				this.src = this.src.replace('.png','_.png');
				$(this).addClass('checkedFeedback');
				climateprojects.currentFeedback = this.id.replace('Link','');
				if(!climateprojects.feedbackChanged){
					$('#feedbackText').addClass('grey');
					$('#feedbackText').addClass('untouched');
					$('#feedbackText').val($(this).attr('alt'));
					$('#feedbackText').one('focus',function(){
						$(this).removeClass('grey');
						$(this).removeClass('untouched');
						$(this).val('');
					});
				}
				
			});
			$('#feedbackSubmitButton').bind('click', function(){
				if($('#feedbackText').val().length > 5 && !$('#feedbackText').hasClass('untouched')){
					sendVars({
					    'module_fnc[spota]':'ExecuteAjaxCall'
					    ,'_fnc':'SendEMail'
					    ,feedbacktype:climateprojects.currentFeedback
					    ,feedbackText:$('#feedbackText').val()
						,email:$('#emailField').val()
						,callbackFunction:'feedbackComplete'
					    },
					    'http://' + window.location.host + '/Hidden/Feedback.html'
					);
				}
				else if ($('#feedbackText').hasClass('untouched')){
					alert('Please enter a message');
				}
				else {
					alert('Please enter at least 5 chars...');
				}
				return false;
			});
			$('#feedbackFormWrapper #feedbackText').bind('keyup',function(){
				climateprojects.feedbackChanged = true;
				if(climateprojects.currentFeedback > 0 && $('#feedbackText').val().length > 5){
					$('#feedbackSubmitButton').removeClass('grey');
					$('#feedbackSubmitButton').addClass('green');
					
				}
				else {
					$('#feedbackSubmitButton').addClass('grey');
					$('#feedbackSubmitButton').removeClass('green');
					
				}
			});
			$('#feedbackFormWrapper').css('top', parseInt(($(window).height() - 260) / 2) + 'px');
			$('#feedbackFormWrapper').css('left', parseInt(($(window).width() - 280) / 2) + 'px');
		}
		else {
			$('#feedbackFormWrapper').show();
			$('#feedbackFormWrapper').css('z-index',$('#TB_overlay').css('z-index')+1);
		}
		
		return false;
	}
	
	,feedbackComplete : function(response){
		if(response && response.mailSent){
			message = '<p>Message was sent.</p><p>Thank you for your feedback!</p><br />';
		}
		else {
			message = '<p class="red">Sorry, an error occured.<br />Your message could not be delivered</p><br />';
		}
		message += '<button class="button" onclick="climateprojects.closeFeedbackForm();">Close</button>';
		$('#feedbackFormWrapper').html(message);
		climateprojects.currentFeedback = 0;
	}
	
	
	,closeFeedbackForm: function(){
		$('#feedbackFormWrapper').remove();
		tb_remove();
		return false;
	}
	
	
	
	,validateEmail: function(value){
		var reg = /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
		return reg.test(value);
	}
}


function sendVars(varObj,url){
	
		/**
		 * sends vars via ajax to the server 
		 * expects a _fnc property containing the function name of the serverside module or callback property 
		 * @param {Object} varObj
		 * @param {Object} url
		 */
		if(typeof url == 'undefined')url = defaultAjaxUrl;
		options = {
			url: url,
			processData: true,
			data: varObj,
			dataType: 'json',
			type: 'POST'
		};
		if(typeof varObj.dataType != 'undefined'){
			options.dataType = varObj.dataType;
		}
		// the callback function should have th cp object accessible as this, so we have to apply the cp object
		
		if (typeof varObj.callbackFunction != 'undefined'){
			if(typeof widget[varObj.callbackFunction] == 'function') {
				options.success = function(data, status){
					widget[varObj.callbackFunction].apply(widget, arguments);
				}
			} 
			else if(typeof climateprojects[varObj.callbackFunction] == 'function') {
				options.success = function(data, status){
					climateprojects[varObj.callbackFunction].apply(climateprojects, arguments);
				}
			} 
			else options.success = varObj.callbackFunction;
		}
		else if (typeof varObj._fnc != 'undefined'){
			if (typeof widget[varObj._fnc + 'Complete'] == 'function') {
				options.success = function(data, status){
					// set the scope for the success function to the cp object
					widget[varObj._fnc + 'Complete'].apply(widget, arguments);
				}
			}
			else if(typeof climateprojects[varObj._fnc] == 'function') {
				options.success = function(data, status){
					climateprojects[varObj._fnc].apply(climateprojects, arguments);
				}
			} 

		}
		options.error = function(data, error, obj){
			alert('Sorry, an error occured!');
		};
		
		$.ajax(options);
		
}

function getLL(key){
	if(typeof ll[key] != 'undefined'){
		return ll[key];
	}
	else return key;
}

function OpenPopupWindow(url, name, w, h, showScrollbar) {
  // Fudge factors for window decoration space.
  // In my tests these work well on all platforms & browsers.
  w += 32;
  h += 96;
  wleft = (screen.width - w) / 2;
  wtop = (screen.height - h) / 2;
  // IE5 and other old browsers might allow a window that is
  // partially offscreen or wider than the screen. Fix that.
  // (Newer browsers fix this for us, but let's be thorough.)
  if (wleft < 0) {
    w = screen.width;
    wleft = 0;
  }
  if (wtop < 0) {
    h = screen.height;
    wtop = 0;
  }
  var winParam = 'width=' + w + ', height=' + h + ', ' + 'left=' + wleft + ', top=' + wtop + ', location=no, menubar=no, status=no, toolbar=no, resizable=no';
  if (showScrollbar) winParam = winParam + ", scrollbars=yes";
  else winParam = winParam + ", scrollbars=no";
  var win = window.open(url, name, winParam );
  // Just in case width and height are ignored
  win.resizeTo(w, h);
  // Just in case left and top are ignored
  win.moveTo(wleft, wtop);
  win.focus();
  return false;
}
