/**
 * define a base namespace
 */
if(typeof Portal == 'undefined'){
	var Portal = {};
}
/**
 * MessageBox Static Class(Object)
 */
Portal.MessageBox = {
	/**
	 * DOM element
	 */
	dom:null,
	/**
	 * default width
	 */
	width:400,
	/**
	 * default height
	 */
	height:100,
	/**
	 * element storage for openElement() method.
	 */
	elm:null,
	/**
	 * element container
	 */
	elmContainer:null,
	/**
	 * Initialization
	 */
	initialize:function(){
		var div = document.createElement('div');
		document.body.appendChild(div);
		this.dom = $(div);
		$(this.dom).dialog({width:this.width,height:this.height,autoOpen:false});
	},
	/**
	 * open a message box and display the given message, if width and height are given, message box will be resized.
	 * @param {String} msg		message
	 * @param {Int} width	message box width
	 * @param {Int} height	message box height
	 */
	open:function(msg,width,height){
		if(this.dom == null){
			this.initialize();
		}
		this.restoreElement();
		if(msg){
			$(this.dom).html(msg);
		}
		this.resize(width,height);
		$(this.dom).dialog('open');
	},
	/**
	 * open a message box and show a DOM element in it, if width and height are given, message box will be resized.
	 * @param {HTMLElement} elm		DOM element
	 * @param {Int} width	message box width
	 * @param {Int} height	message box height
	 */
	openElement:function(elm,width,height){
		if(this.dom == null){
			this.initialize();
		}
		this.restoreElement();
		this.elm = elm;
		this.elmContainer = elm.parentNode;
		$(this.dom).html('').append(elm);
		this.resize(width,height);
		$(this.dom).dialog('open');
		
	},
	/**
	 * close current message box
	 */
	close:function(){
		$(this.dom).dialog('close');
	},
	/**
	 * remove element from message box and put it back to its own container.
	 */
	restoreElement:function(){
		if(this.elm){
			$(this.elmContainer).append(this.elm);
			this.elm = null;
			this.elmContainer = null;
		}
	},
	/**
	 * resize a message box
	 * @param {Int} width	message box width
	 * @param {Int} height	message box height
	 */
	resize:function(width,height){
		$(this.dom).dialog('option','width',width || this.width);
		$(this.dom).dialog('option','height',height || this.height);
		var _this = this;
		setTimeout(function(){
			$('.ui-dialog').css({
				'width': (width || _this.width) + 'px',
				'height': (height || _this.height) + 'px'
			});
			$('.ui-dialog-content').css({'height':'auto'});
		},1);
	}
}

/**
 * override window's default alert behavior
 * replace the default alert box with Portal.MessageBox
 */
window._alert = window.alert;
window.alert = function(message){
	try{
		Portal.MessageBox.open(message);
	}catch(e){
		window._alert(message);
	}
}
/**
 * Form Class
 * Constructor
 * @param {Object} config	config datas
 * 	options:
 * 		config.steps		{Array}		multiple steps' containers
 * 		config.form			{String}	form element
 * 		config.formCallback	{Function}	form submitting event handler
 */
Portal.Form = function(config){
	this.config = $.extend({
		'steps':['#register_rule','#register_form','#register_success'],
		'form':'#register-form',
		'formCallback':null
	},config || {});
	this.steps = [];
	this.initialize();
}
/**
 * Form's properties and methods
 */
Portal.Form.prototype = {
	/**
	 * Initialize
	 */
	initialize:function(){
		var _this = this;
		$.each(this.config.steps,function(n,step){
			_this.steps.push(step);
		});
		this.validator = new Portal.Validator({form:this.config.form});
		$(this.config.form).submit(function(){_this.submitRegisterForm()});
	},
	/**
	 * Jump to a step
	 * @param {Int} i	step
	 */
	goStep:function(i){
		var _this = this;
		$.each(this.steps,function(n,step){
			if(_this.steps[i - 1] == step){
				$(step).show();
			} else {
				$(step).hide();
			}
		});
	},
	/**
	 * validate form
	 * @return	{Bool}	validation status
	 */
	validate:function(){
		return this.validator.validate();
	},
	/**
	 * Submit form via AJAX
	 */
	submitRegisterForm:function(){
		if(this.validate()){
			var data = $(this.config.form).formSerialize(); 
			var _this = this;
			//$.getJSON($(this.config.form).attr('action'),data, _this.config.formCallback || function(){});
			$.ajax({
				type:'POST',
				url:$(this.config.form).attr('action'),
				dataType:'json',
				data:data,
				success:_this.config.formCallback || function(){}
			});
		}
	},
	/**
	 * reset form
	 */
	resetForm:function(){
		this.validator.reset();
	}
}
/**
 * Validator Class
 * Constructor
 * @param {Object} config	config data
 * 	options:
 * 		config.form			{String}	form element
 * 		config.showAdvices	{Bool}		show advices(use titles as advices) or not 
 */
Portal.Validator = function(config){
	this.config = $.extend({
		'form':null,
		'showAdvices':true
	},config || {});
	if(this.config.form){
		this.fields = $('.validate', $(this.config.form));
	} else {
		this.fields = $('.validate');
	}
	this.fields.each(function(i,field){
		$(field).focus(function(){
			$(field).removeClass('error');
			if(field.advice)$(field.advice).hide();
		})
	});
}
/**
 * Validator's properties and methods.
 */
Portal.Validator.prototype = {
	/**
	 * validate form
	 * @return	{Bool}	validation status
	 */
	validate:function(){
		var result = true;
		var _this = this;
		this.fields.each(function(i,field){
			if(!_this.validateField(field)){
				result = false;
				$(field).addClass('error');
			} else {
				$(field).removeClass('error');
			}
		})
		if(!result && this.config.showAdvices){
			this.showAddvices();
		}
		return result;
	},
	/**
	 * validate field
	 * @param {FormElement} field	form field element
	 * @return {Bool}	validation status
	 */
	validateField:function(field){
		var result = true;
		$.each(Portal.Validator.Rules,function(cs,fn){
			if($(field).hasClass(cs)){
				if(! fn(field)) result = false;
			}
		});
		return result;
	},
	/**
	 * reset all fields
	 */
	reset:function(){
		this.fields.each(function(i,field){
			$(field).removeClass('error');
			if(field.advice)$(field.advice).hide();
		});
		if(this.config.form)$(this.config.form)[0].reset();
	},
	/**
	 * show addvices(error messages)
	 */
	showAddvices:function(){
		this.fields.each(function(i,field){
			if($(field).hasClass('error') && $(field).attr('title')){
				if(field.advice){
					$(field.advice).show();
					return;
				}
				var advice = document.createElement('div');
				$(advice).addClass('validator-advice');
				$(advice).html($(field).attr('title'));
				field.advice = advice;
				if($(field).hasClass('absolute-advice')){
					var offset = $(field).offset();
					offset.top += $(field).height();
					$(advice).css($.extend({
						'position':'absolute',
						'zIndex':'100'
					},offset));
					$(advice).appendTo(document.body);
				}else{
					$(field).after(advice);
				}
			}
		});
	}
}
/**
 * Validator Rules Object
 */
Portal.Validator.Rules = {
	'required':function(field){
		return !/^\s*$/g.test(field.value);
	},
	'validate-email':function(field){
		return /^\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*$/i.test(field.value);
	},
	'validate-username':function(field){
		return /^(\w|\d){4,}$/.test(field.value);
	},
	'validate-password':function(field){
		return /^(\w|\d){4,}$/.test(field.value);
	},
	'validate-cemail':function(field){
		return $('.validate-email')[0].value == field.value;
	},
	'validate-old-password':function(field){
		if(Portal.Validator.Rules['required'](field)){
			return Portal.Validator.Rules['validate-password'](field);
		} else {
			return true;
		}
	},
	'validate-new-password':function(field){
		if(Portal.Validator.Rules['required'](field)){
			if(Portal.Validator.Rules['validate-password'](field)){
				if(! Portal.Validator.Rules['validate-password']($('.validate-old-password')[0])){
					$('.validate-old-password').addClass('error');
					return false;
				} else {
					return true;
				}
			} else {
				return false;
			}
		} else {
			return true;
		}
	},
	'validate-cnew-password':function(field){
		if($('.validate-new-password')[0].value != field.value){
			return false;
		} else {
			return true;
		}
	},
	'validate-positive-integer':function(field){
		return /^[1-9]+[0-9]*$/.test(field.value);
	},
	'validate-integer':function(field){
		return /^(\+|\-)?\d+$/.test(field.value);
	},
	'validate-not-default':function(field){
		return !/^\s*$/g.test(field.value) && field.clicked;
	}
}
/**
 * ImageList Class
 * Constructor
 * @param {Object} config 	config data
 * 	options:
 * 		config.listContainer	{HTMLElement}	image list container
 * 		config.childrenTag		{String}		HTML tag, used by image item
 */
Portal.ImageList = function(config){
	this.items = [];
	this.config = $.extend({
		'listContainer':'#image_list',
		'childrenTag':'dd'
	},config || {});
	this.initialize();
}
/**
 * ImageList's properties and methods
 */
Portal.ImageList.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		var _this = this;
		var maxHeight = 0;
		$(this.config.listContainer + ' ' + this.config.childrenTag).each(function(i,n){
			maxHeight = n.offsetHeight > maxHeight ? n.offsetHeight : maxHeight;
			var favoriteCheckBox = $('div.image_action a',$(n))[0];
			var reportButton = $('div.image_action a',$(n))[1];
			var nid = $(n).attr('id').replace('node-','');
			var img = new Portal.Image(nid, {
				favoriteCheckBox:favoriteCheckBox,
				report:{
					reportButton:reportButton	
				}
			});
			_this.items.push(img);
			if($('img.geo-sign',$(n)).length > 0){
				$('img.geo-sign',$(n)).css('cursor','pointer');
				$('img.geo-sign',$(n)).click(function(){
					img.showGmap();
				})
			}
		})
		$(this.config.listContainer + ' ' + this.config.childrenTag).each(function(i,n){
			n.style.height = maxHeight + 'px';
		});
		$('.image_action').css({
			'position':'absolute',
			'bottom':'5px',
			'left':'6px'
		});
	}
}
/**
 * Image Class
 * Constructor
 * @param {Int} nid			Node id
 * @param {Object} config	config data
 * 	options:
 * 		config.favoriteCheckbox		{HTMLElement}	favorite controller element
 * 		config.voting				{Object}		voting options
 * 		config.comment				{Object}		comment options
 * 		config.ecard				{Object}		ecard options
 * 		config.report				{Object}		report options
 */
Portal.Image = function(nid,config){
	this.config = $.extend({
		favoriteCheckBox:null
	},config || {});
	this.nid = nid;
	this.initialize();
	Portal.Image.Instances.push(this);
}
/**
 * Global Image Instances Array
 */
Portal.Image.Instances = [];
/**
 * Image's properties and methods.
 */
Portal.Image.prototype = {
	/**
	 * Initialization.
	 */
	initialize:function(){
		if(this.config.favoriteCheckBox){
			this.favorite = new Portal.Favorite(this.nid, this.config.favoriteCheckBox, this.config.favoriteUpdateUrl || Portal.basePath + 'ajaxprocess/updatefavoritestate');
		}
		if(this.config.voting){
			this.voting = new Portal.Voting(this.nid, this.config.voting);
		}
		if(this.config.comment){
			this.comment = new Portal.Comment(this.nid, this.config.comment);
		}
		if(this.config.ecard){
			this.ecard = new Portal.Ecard(this.nid, this.config.ecard);
		}
		if(this.config.report){
			this.report = new Portal.Report(this.nid,this.config.report);
		}
		this.gmapFrame = null;
	},
	showGmap:function(){
		if(this.gmapFrame == null){
			Portal.Iframe.createNewIframe('gmap' + this.nid, Portal.basePath + 'map/node/' + this.nid, 650, 520);
			this.gmapFrame = $('#' + 'gmap' + this.nid).css('border','0');
		}
		Portal.MessageBox.openElement(this.gmapFrame, 680, 580);
	}
}
/**
 * Class Favorite
 * Constructor
 * @param {Int} nid				node id
 * @param {HTMLElement} dom		controller element
 * @param {String} url			BE service url
 */
Portal.Favorite = function(nid,dom,url){
	this.nid = nid;
	this.dom = dom;
	this.url = url;
	this.enable = $(dom).hasClass('button_enabled');
	this.initialize();
}
/**
 * CHECKED STATUS STYLE CLASS NAME
 * static property
 */
Portal.Favorite.CHECKED = 'leuchtkasten_checked';
/**
 * UNCHECKED STATUS STYLE CLASS NAME
 * static property
 */
Portal.Favorite.UNCHECKED = 'leuchtkasten';
/**
 * Remove favorites
 * static method
 * @param {String} type		list view type
 */
Portal.Favorite.deleteFavorites = function(type){
	if(arguments.length == 0)return;
	var url = Portal.basePath + 'ajaxprocess/deletefavorites';
	for(var i = 0,l = arguments.length; i < l; i ++) {
		url += '/' + arguments[i];
	}
	$.getJSON(url,function(result){
		Portal.MessageBox.open(result.message);
		if(type == 'favorites') {
			setTimeout(function(){
				window.location.reload();
			},1000);
		}
		$.each(Portal.Image.Instances, function(i, img){
			if(img.favorite && img.favorite.favorite){
				$(img.favorite.dom).removeClass(Portal.Favorite.CHECKED);
				$(img.favorite.dom).addClass(Portal.Favorite.UNCHECKED);
				img.favorite.favorite = false;
			}
		})
	})
}
/**
 * Favorite's properties and methods
 */
Portal.Favorite.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		var _this = this;
		$(this.dom).click(function(){
			if(Portal.uid == 0) {
				Portal.MessageBox.open(Portal.Translations['unlogin']);
			}else if(_this.enable){
				_this.toggleFavoriteState();
			}
			return false;
		})
		if($(this.dom).hasClass(Portal.Favorite.CHECKED)){
			this.favorite = true;
		}else{
			this.favorite = false;
		}
	},
	/**
	 * Toggle favorite state
	 */
	toggleFavoriteState:function(){
		if(this.favorite){
			$(this.dom).removeClass(Portal.Favorite.CHECKED);
			$(this.dom).addClass(Portal.Favorite.UNCHECKED);
			this.updateFavoriteState(false);
		} else {
			$(this.dom).removeClass(Portal.Favorite.UNCHECKED);
			$(this.dom).addClass(Portal.Favorite.CHECKED);
			this.updateFavoriteState(true);
		}
	},
	/**
	 * Update favorite state to DB
	 * @param {Bool} state	is in favorite or not
	 */
	updateFavoriteState:function(state){
		this.favorite = !!state;
		$.getJSON(this.url + '/' + this.nid + '/' + (this.favorite ? 1 : 2) ,function(result){
			//Portal.MessageBox.open(result.message);
		})
	}
}
/**
 * Voting Class
 * Constructor
 * @param {Int} nid			node id
 * @param {Object} config	config data
 * 	options:
 * 		config.selector			{HTMLElement}	selector controller
 * 		config.submitBtn		{HTMLElement}	submitting button
 * 		config.url				{String}		BE service url
 * 		config.disabledPropText	{String}		notice text when voting is disabled
 * 		config.onVotingSaved	{String}		notice text when voting is saved
 */
Portal.Voting = function(nid,config){
	this.nid = nid;
	this.config = $.extend({
		'selector':'#voting-values',
		'submitBtn':'#voting-submit-btn',
		'url':Portal.basePath + 'ajaxprocess/savevoting',
		'disabledPropText':'You had voted for this picture already.',
		'onVotingSaved':function(){}
	}, config || {});
	this.enable = true;
	this.initialize();
}
/**
 * Voting's properties and method.
 */
Portal.Voting.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		var _this = this;
		if($(this.config.selector).attr('disabled')){
			this.enable = false;
		}
		$(this.config.submitBtn).click(function(){
			if(_this.enable){
				_this.updateVoting();
			} else {
				Portal.MessageBox.open(_this.config.disabledPropText);
			}
			return false;
		})
	},
	/**
	 * update voting data of one image
	 */
	updateVoting:function(){
		var _this = this;
		var value = $(this.config.selector)[0].value;
		$.getJSON(this.config.url + '/' + this.nid + '/' + value ,function(result){
			if(!result.state)Portal.MessageBox.open(result.message);
			//$(_this.config.selector).attr('disabled','disabled');
			//_this.enable = false;
			if(result.state && _this.config.onVotingSaved){
				_this.config.onVotingSaved(result.votingresult);
			}
		});
	}
}
/**
 * Class Comment
 * Constructor
 * @param {Int} nid			node id
 * @param {Object} config	config data
 * 	options:
 * 		config.form					{FormElement}	comment form
 * 		config.commentsContainer	{HTMLElement}	comments list container
 * 		config.commentsUpdateUrl	{String}		BE service url
 * 		config.onPosting			{Function}		on comment posting event handler
 * 		config.onValidateFail		{Function}		on comment form validation failed event handler
 */
Portal.Comment = function(nid,config){
	this.nid = nid;
	this.config = $.extend({
		'form':'#comment-post-form',
		'commentsContainer':'#comments-container',
		'commentsUpdateUrl':Portal.basePath + 'ajaxprocess/comments/view',
		'onPosting':function(){},
		'onPosted':function(){},
		'onValidateFail':function(){}
	}, config || {});
	this.posting = false;
	this.initialize();
}
/**
 * Comment's properties and methods
 */
Portal.Comment.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		this.validator = new Portal.Validator({form:this.config.form});
	},
	/**
	 * post a comment
	 */
	postComment:function(){
		if(this.posting)return;
		this.posting = true;
		this.config.onPosting(this);
		var _this = this;
		if(this.validator.validate()){
			$(this.config.form).ajaxSubmit({
				url:$(this.config.form).attr('action') + '/' + this.nid,
				dataType:'json',
				success:function(result){
					if(result.state){
						_this.resetForm();
						_this.updateCommentsList();
					} else {
						Portal.MessageBox.open(result.message);
					}
					_this.posting = false;
					_this.config.onPosted(_this);
				}
			});
		}else{
			_this.posting = false;
			_this.config.onValidateFail(_this);
		}
	},
	/**
	 * update comment list
	 */
	updateCommentsList:function(){
		var _this = this;
		$(this.config.commentsContainer).slideUp();
		$.getJSON(this.config.commentsUpdateUrl + '/' + this.nid ,function(result){
			$('.comments-count', $(_this.config.commentsContainer)).html('(' + result.count + ')');
			$('.comments-list', $(_this.config.commentsContainer)).html(result.comments);
			$(_this.config.commentsContainer).slideDown();
		});
	},
	/**
	 * reset comment form
	 */
	resetForm:function(){
		$(this.config.form)[0].reset();
		this.validator.reset();
	}
}
/**
 * Class Ecard
 * Constructor
 * @param {Int} nid			node id
 * @param {Object} config	config data
 * 	options:
 * 		config.form			{FormElement}		Ecard form
 * 		config.sendUrl		{String}			BE service url for sending ecard
 * 		config.reviewUrl	{String}			BE service url for ecard review
 * 		config.successNotice{String}			notice text on success sending
 * 		config.faledNotice	{String}			notice text on failed sending
 * 		config.callback		{Function}			sending complete event handler
 */
Portal.Ecard = function(nid, config){
	this.nid = nid;
	this.config = $.extend({
		'form':'#ecard-form',
		'sendUrl':Portal.basePath + 'ecard/send',
		'reviewUrl':Portal.basePath + 'ecard/review',
		'successNotice':'',
		'failedNotice':'',
		'callback':function(){}
	}, config || {});
	this.initialize();
}
/**
 * Ecard's properties and methods
 */
Portal.Ecard.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		this.validator = new Portal.Validator({form:this.config.form});
	},
	/**
	 * validate form
	 * @return	{Bool}	validation status
	 */
	validate:function(){
		return this.validator.validate();
	},
	/**
	 * send a eacrd
	 */
	send:function(){
		if(!this.validate())return;
		var _this = this;
		$.getJSON(this.config.sendUrl, $(this.config.form).formSerialize(), function(result){
			if(result.result){
				Portal.MessageBox.open(_this.config.successNotice);
			} else {
				Portal.MessageBox.open(_this.config.failedNotice);
			}
			_this.config.callback(result);
		});
	},
	/**
	 * review a ecard
	 */
	review:function(){
		if(!this.validate())return;
		$.ajax({
			type:'post',
			url:this.config.reviewUrl,
			data:$(this.config.form).formSerialize(),
			success:function(msg){
				Portal.MessageBox.open(msg,650,500);
			}
		})
	}
}
/**
 * Class Report
 * Constructor
 * @param {Int} nid			node id
 * @param {Object} config	config data
 * 	options:
 * 		config.reportButton		{HTMLElement}	report button
 */
Portal.Report = function(nid,config){
	this.nid = nid;
	this.config = $.extend({
		reportButton:null
	},config || {});
	this.initialize();
}
/**
 * Report's properties and method
 */
Portal.Report.prototype = {
	/**
	 * Initialization
	 */
	initialize:function(){
		this.enable = $(this.config.reportButton).hasClass('button_enabled');
		var _this = this;
		$(this.config.reportButton).click(function(){
			if(Portal.uid == 0) {
				Portal.MessageBox.open(Portal.Translations['unlogin']);
			}else if(_this.enable){
				_this.report();
			}
			return false;
		});
	},
	/**
	 * do a report
	 */
	report:function(){
		if(!this.enable)return;
		var _this = this;
		Portal.Report.Form.onSubmit = function(result){
			$(_this.config.reportButton).removeClass('button_enabled');
			$(_this.config.reportButton).addClass('button_disabled');
			_this.enable = false;
			setTimeout(function(){
				$(_this.config.reportButton).removeClass('button_disabled');
				$(_this.config.reportButton).addClass('button_enabled');
				_this.enable = true;
			},result.interval * 1000);
		}
		Portal.Report.Form.show(this.nid);
	}
}
/**
 * Report Form Object
 * static Class
 */
Portal.Report.Form = {
	/**
	 * form storage
	 */
	form:null,
	/**
	 * form validator
	 */
	validator:null,
	/**
	 * BE service url for reporting
	 */
	submitUrl:Portal.basePath + 'ajaxprocess/report',
	/**
	 * onsubmit event handler
	 */
	onSubmit:function(){},
	/**
	 * onprocessing event handler
	 */
	onProcessing:false,
	/**
	 * Initialization
	 */
	init:function(){
		if(this.form == null){
			var form = '<form name="report-form" id="report-form" method="post" action="' + this.submitUrl + '" style="width:450px;">'
					+ '<div class="form_label bold">'
					+ 	'<label for="report-title">Titel</label>'
					+ 	'<span class="form-required">*</span>'
					+ '</div>'
					+ '<div class="form_element">'
					+ 	'<input id="report-title" class="textbox validate required" type="text" title="Dies ist ein Pflichtfeld." name="report[title]"/>'
					+ '</div>'
					+ '<div class="form_label bold">'
					+ 	'<label for="report-content">Bericht</label>'
					+ 	'<span class="form-required">*</span>'
					+ '</div>'
					+ '<div class="form_element">'
					+ 	'<textarea id="report-content" class="textarea validate required" title="Dies ist ein Pflichtfeld." cols="" rows="" name="report[content]"/>'
					+ '</div>'
					+ '<input type="hidden" name="report[nid]" id="report-nid" value="" />'
					+ '<div class="register_action for_form">'
					+ 	'<a class="button" id="report-submit-button" href="#">Absenden</a>'
					+ 	'<a class="button" id="report-reset-button" href="#">Zurücksetzen</a>'
					+ '</div>'
					+ '<div class="form_blank"/>'
					+ '</form>';
					
			var div = document.createElement('div');
			div.style.display = 'none';
			$(div).append(form);
			$(document.body).append(div);
			this.form = $('#report-form')[0];
			
			this.validator = new Portal.Validator({form:'#report-form'});
			$('#report-submit-button').click(function(){
				Portal.Report.Form.submit();
				return false;
			})
			$('#report-reset-button').click(function(){
				Portal.Report.Form.validator.reset();
				return false;
			})
			$('#report-form').submit(function(){
				Portal.Report.Form.submit();
				return false;
			})
		}
	},
	/**
	 * show reporting form
	 * @param {Int} nid	node id
	 */
	show:function(nid){
		if(this.onProcessing)return;
		this.init();
		Portal.MessageBox.openElement(this.form,450,260);
		$('#report-nid')[0].value = nid;
	},
	/**
	 * submit reporting form
	 */
	submit:function(){
		if(this.validator.validate()){
			this.onProcessing = true;
			$('#report-form').ajaxSubmit({
				dataType:'json',
				success:function(result){
					Portal.MessageBox.open(result.message);
					Portal.Report.Form.onSubmit(result);
					Portal.Report.Form.onProcessing = false;
					Portal.Report.Form.validator.reset();
				}
			});
		}
	}
}
/*
Portal.AutoComplete = function(dom,options){
	this.dom = dom;
	this.startPoint = options.startPoint || 3;
	this.JSONService = options.JSONService;
	this.selector = new Portal.AutoCompleteSelector(this,options.selector);
	var __this = this;
	this.selectMode = true;
	var _eventHandler = function(){
		setTimeout(function(){
			if(__this.dom.cacheValue != __this.dom.value){
				__this.dom.cacheValue = __this.dom.value;
				__this.search();
			}else{
				if(__this.dom.value.length >= __this.startPoint)__this.selector.show();	
			}
		},10);
	}
	$(this.dom).focus(_eventHandler);
	$(this.dom).change(_eventHandler);
	$(this.dom).keyup(_eventHandler);
}

Portal.AutoComplete.prototype = {
	request:null,
	dataCache:null,
	createXMLHttpRequest:function(){
		try{
			return new XMLHttpRequest();	
		}catch(e){
			return new ActiveXObject('Microsoft.XMLHTTP');	
		}
	},
	search:function(){
		var keyword = this.dom.value;
		if(keyword.length < this.startPoint)return;
		if(this.request)this.request.abort();
		this.request = this.createXMLHttpRequest();
		var request = this.request;
		request.open('GET',this.JSONService + '?keyword=' + escape(keyword),true);
		var __this = this;
		request.onreadystatechange = function(){
			if(request.readyState == 4 && request.status == 200){
				var data = eval('(' + request.responseText + ')');
				__this.parseData.call(__this,data);
			}
		}
		request.send(null);
	},
	parseData:function(data){
		this.dataCache = data;
		this.selector.load(data);
		if(this.selector.dom.getElementsByTagName('div').length > 0){
			this.selector.show();
		}else{
			this.selector.hide();	
		}
	}
}

//AutoCompleteSelector Class
Portal.AutoCompleteSelector = function(autoCompleteObject){
	this.autoCompleteObject = autoCompleteObject;
	if(arguments[1]){
		this.dom = arguments[1];
	}else{
		this.dom = this.createDefaultSelectorElement();	
	}
}

Portal.AutoCompleteSelector.prototype = {
	createDefaultSelectorElement:function(){
		var target = this.autoCompleteObject.dom;
		var left = target.offsetLeft;
		var top = target.offsetTop + target.offsetHeight + 1;
		var width = target.offsetWidth;
		while(target.parentNode != document.body){
			target = target.parentNode;
			left += target.offsetLeft;
			top += target.offsetTop;
		}
		var div = document.createElement('div');
		div.className = 'autoCompleteSelector';
		div.style.position = 'absolute';
		div.style.left = left + 'px';
		div.style.top = top + 'px';
		div.style.width = width + 'px';
		div.style.height = 'auto';
		div.style.overflow = 'auto';
		div.style.display = 'none';
		div.style.zIndex = 1000;
		div.style.border = '1px solid #999';
		document.body.appendChild(div);
		div.autoCompleteSelectorObject = this;
		return div;
	},
	dataCache:[],
	show:function(){
		this.dom.style.display = 'block';
	},
	hide:function(){
		this.dom.style.display = 'none';
	},
	load:function(data){
		this.clear();
		for(var i = 0; i < data.length; i ++){
			this.add(new Portal.AutoCompleteSelectItem(data[i],this));
		}
	},
	clear:function(){
		this.dom.innerHTML = '';
	},
	add:function(item){
		this.dom.appendChild(item.dom);	
	},
	remove:function(item){
		this.dom.removeChild(item.dom);	
	}
}

//AutoCompleteSelectItem Class
Portal.AutoCompleteSelectItem = function(data,autoCompleteSelectorObject){
	this.name = data.name;
	this.value = data.value;
	this.dataCache = data;
	this.autoCompleteSelectorObject = autoCompleteSelectorObject;
	this.dom = this.create();
	var __this = this;
	$(this.dom).click(function(){
		__this.autoCompleteSelectorObject.autoCompleteObject.dom.cacheValue = __this.name;
		__this.autoCompleteSelectorObject.autoCompleteObject.dom.value = __this.name;
		__this.autoCompleteSelectorObject.hide();
	});
}
Portal.AutoCompleteSelectItem.prototype = {
	create:function(){	
		var div = document.createElement('div');
		div.className = 'autoCompleteSelectItem';
		div.style.width = '100%';
		div.style.height = '20px';
		div.style.fontSize = '12px';
		div.style.lineHeight = '20px';
		div.style.textAlign = 'left';
		div.style.padding = '2px';
		div.style.borderBottom = '1px solid #ccc';
		div.style.color = '#000';
		div.style.backgroundColor = '#fff';
		div.onmouseover = function(){
			this.style.backgroundColor = '#999';
			this.style.color = '#fff';
			this.style.cursor = 'pointer';
		}
		div.onmouseout = function(){
			this.style.backgroundColor = '#fff';
			this.style.color = '#000';
		}
		div.innerHTML = this.name;
		div.autoCompleteSelectItem = this;
		return div;
	}
}
*/
Portal.Iframe = {
	iframe:null,
	init:function(){
		$(document.body).append('<iframe name="portal-iframe" id="portal-iframe" src="about:blank" style="display:none;"></iframe>');
		this.iframe = 'portal-iframe';
	},
	submitForm:function(form){
		if(this.iframe == null){
			this.init();
		}
		form.target = 'portal-iframe';
		form.submit();
	},
	openUrl:function(url){
		if(this.iframe == null){
			this.init();
		}
		window.frames[this.iframe].location.href = url + (/\?/.test(url) ? '&timestamp=' : '?timestamp=') + new Date().getTime();
	},
	createNewIframe:function(name,url,width,height){
		var div = document.createElement('div');
		$(div).append('<iframe name="' + name + '" id="' + name + '" src="'+ url + '" width="' + width + '" height="' + height + '" border="0" style="overflow:hidden;border:0;"></iframe>');
		$(document.body).append(div);
	}
}
/**
 * close all info window on a gmap
 */
function closeAllInfoWindow(){
  	var mapObject = Drupal.gmap.getMap('gmap-nodemap-gmap0');
  	var map = mapObject.map;
  	map.closeExtInfoWindow();
}

function toggleLinkButton(btn){
	if($(btn).hasClass('button_disabled')) {
		$(btn).removeClass('button_disabled');
		$(btn).addClass('button_enabled');
	} else {
		$(btn).addClass('button_disabled');
		$(btn).removeClass('button_enabled');
	}
}

Portal.ImageUploader = function(container,options){
	this.container = container;
	this.count = 0;
	this.fileQueue = [];
	this.uploadIndex = 0;
	this.options = $.extend({
		exts: ['jpg','png','gif'],
		size: 5*1024*1024,
		uploadifyPath: Portal.basePath + 'sites/all/themes/zen/fotoportal/js/uploadify/',
		multi:false,
		texts: {
			buttonText: 'Browse',
			errorExtText: 'Error extension',
			errorSizeText: 'Error file size'
		},
		onAllComplete:function(){}
	},options || {});
	this.initialize();
	Portal.ImageUploader.Instances.push(this);
}
Portal.ImageUploader.Instances = [];
Portal.ImageUploader.prototype = {
	initialize:function(){
		var _this = this;
		$(this.container).fileUpload({
			'uploader': this.options.uploadifyPath + '/uploader.swf',
			'cancelImg': this.options.uploadifyPath + '/cancel.png',
			'script': Portal.basePath + 'portal/image/saveimage',
			'buttonText': this.options.texts.buttonText,
			'multi': this.options.multi,
			'simUploadLimit': 1,
			'buttonImg': this.options.uploadifyPath + '/button_3.jpg',
			'rollover': true,
			'width': 90,
			'height': 17,
			'fileExt': '*.jpg;*.gif;*.png',
			'fileDesc': '*.jpg;*.gif;*.png',
			'wmode': 'transparent',
			'onSelect': function(e, qid, file){
				var val = _this.validateFile(e, qid, file);
				_this.count ++;
				_this.fileQueue.push(qid);
				if(!val){
					$(_this.container).fileUploadCancel(qid);
				}
				return val;
			},
			'onCancel':function(e, qid, file, data){
				_this.count --;
				var newQueue = [];
				for(var i = 0; i < _this.fileQueue.length; i ++) {
					if(_this.fileQueue[i] != qid) {
						newQueue.push(_this.fileQueue[i]);
					}
				}
				_this.fileQueue = newQueue;
				return true;
			},
			'onComplete':function(e, qid, file, response, data){
				_this.onComplete(e, qid, file, response, data);
				return false;
			},
			'onAllComplete':function(e, data){
				//_this.options.onAllComplete(e, data);
				return true;
			},
			'onError':function(e,qid,fileObj,errorObj){
				Portal.MessageBox.open('Es ist ein Netzwerkfehler bei der Übertragung aufgetreten. Die Verbindung zum Server wurde verloren.');
				return false;
			}
		});
	},
	validateFile:function(e, qid, file){
		if(file.type == 'null' ) {
            var dot = file.name.lastIndexOf("."); 
            if( dot == -1 ) {
                file.type = "";
            } else {
                file.type = file.name.substr(dot,file.name.length); 
				//window._alert(file.type);
            }
        }
		var type = file.type.replace('.','');
		var inArray = false;
		for(var i = 0; i < this.options.exts.length; i ++){
			if(this.options.exts[i].toLowerCase() == type.toLowerCase()){
				inArray = true;
			}
		}
		if(!inArray){
			Portal.MessageBox.open(this.options.texts.errorExtText);
			return false;
		}
		if(file.size >= this.options.size){
			Portal.MessageBox.open(this.options.texts.errorSizeText);
			return false;
		}
		return true;
	},
	onComplete:function(e, qid, file, response, data){
		var filename = response;
		$(this.options.form).append('<input type="hidden" name="images[]" class="new-images" value="' + filename + '" />');
		this.upload();
	},
	upload:function(){
		if(this.uploadIndex == this.count) {
			this.options.onAllComplete();
		} else {
			$(this.container).fileUploadStart(this.fileQueue[this.uploadIndex]);
			this.uploadIndex ++;
		}
	}
}

$(function(){
	if(!jQuery.browser.msie){
		setTimeout(function(){
			try{
				if(document.getElementById('edit-body')){
					if($('.mceEditor').length == 2) {
						toggletinyMCE('edit-body');
					}
				}
			}catch(e){}
		},0);
	}
})
function imgpos(){
	var ua = navigator.userAgent.toLowerCase();
	var chrome = false;
	try{
	if (window.MessageEvent && !document.getBoxObjectFor){
        chrome = ua.match(/chrome\/([\d.]+)/)[1];
	}
	}catch(e){}
	if(jQuery.browser.safari || chrome) {
		$('#image_list div.image_box img').each(function(i,o){
			var os = - Math.floor(o.height / 2) + 'px';
			o.style.marginTop = os;
		})
	}
}
if(window.addEventListener) {
	window.addEventListener('load',imgpos,false);
}
/*
$(function(){
	if($.browser.msie != true || window.XMLHttpRequest)return;
	$('.image_box img').each(function(i,o){
		if(o.width/o.height >= 179/140){
			if(o.width > 179)o.width = 179;
		} else {
			if(o.height > 140)o.height = 140;
		}
	});
})
*/