var BagExpirePolicy = { 
	Session : [''],
	FifteenMin : [0.15],
	Hour: [1],
	Day : [24],
	Year: [24*365]
};

var BagProperties = { 
//case sensivity!
Properties: [
	'postsPerPage','CountryIndex','Distance','Zip','SearchFemaleGender',
	'SearchMaleGender','ShowName','ShowAddress','ShowActivity','ShowOnlineStatus',
	'ShowProfilePicture','PictureSize','EntriesByPage','PictureCount','MinAgeValue',
	'MaxAgeValue','SortBy','PagerPeoples','DSI','DEI',
	'DIR','postView','filterByDate','filterTagName','showTitle',
	'showTags','pictureSize','picsPerPage','filterSetId','actionName',
	'AlbumMode','sortBy','PagePostView','SearchLoginName','searchTerm',
	'videoView','pageSize'],
	getPropertyID : function(name){
		for(var i=0; i<BagProperties.Properties.length; i++)
			if(BagProperties.Properties[i]==name)
				return i;
		return name;
	}
};
var CookieStateBag = {
  set : function(cookieName,propName,value,expirePolicy){
	if(!cookieName || propName=='')
		return;
	expirePolicy = (!expirePolicy) ? '' : expirePolicy;
	var stateBagName = 'CookieStateBag_'+expirePolicy;
	var cookieNewValue = '';
	propName = BagProperties.getPropertyID(propName);
	value = escape(value);
	var rg = new RegExp('(^|;\\s*)'+stateBagName+'=([^;]*)', 'ig');
	var pattern = rg.exec(document.cookie);
	if(pattern==null)
		cookieNewValue=cookieName+'#'+propName+':'+value;
	else
	{
		var stateBags = new Array();
		var cookieNames = RegExp.$2.split("|");
		var bagFounded = false;
		for(var i=0; i<cookieNames.length; i++){
			var stateBag = new Object();
			var a = cookieNames[i].split("#");
			stateBag.CookieName = a[0];
			if(stateBag.CookieName==cookieName)
				bagFounded = true;
			if(a.length>1){
				var pair = a[1].split('$');
				stateBag.Properties = new Array();
				stateBag.Values = new Array();
				var updated = false;
				for(var j=0; j<pair.length; j++){
					var v = pair[j].split(":");
					stateBag.Properties[stateBag.Properties.length] = v[0];
					if(stateBag.CookieName==cookieName && v[0]==propName) {
						stateBag.Values[stateBag.Values.length] = value;
						updated = true;
					}
					else
						stateBag.Values[stateBag.Values.length] = (v.length>1)?v[1]:'';
				}
			}
			if(stateBag.CookieName==cookieName && !updated) {
				stateBag.Properties[stateBag.Properties.length] = propName;
				stateBag.Values[stateBag.Values.length] = value;
			}
			stateBags[stateBags.length] = stateBag;
		}
		
		if(!bagFounded){
			var stateBag = new Object();
			stateBag.CookieName = cookieName;
			stateBag.Properties = new Array();
			stateBag.Values = new Array();
			stateBag.Properties[0] = propName;
			stateBag.Values[0] = value;
			stateBags[stateBags.length] = stateBag;
		}
		
		for(var i=0; i<stateBags.length; i++){
			if(typeof(stateBags[i].Properties)=='undefined'||stateBags[i].Properties.length==0)
				continue;
			var valStr = '';
			for(var j=0; j<stateBags[i].Properties.length; j++){
				if(valStr.length>0)
					valStr+='$';
				valStr += stateBags[i].Properties[j]+':'+stateBags[i].Values[j];
			}
			if(valStr.length>0) {
				if(cookieNewValue.length>0)
					cookieNewValue+='|';
				cookieNewValue += stateBags[i].CookieName + '#' + valStr;
			}
		}
	}
	var expireString = '';
	if(expirePolicy != '') {
	    if (fractionalPart(expirePolicy)==false){
    	   var currentTime = new Date();
	       currentTime.setHours(currentTime.getHours() + expirePolicy);
	       expireString = 'expires='+currentTime.toGMTString()+';';
		} else {
		   var currentTime = new Date();
	       currentTime.setMinutes(currentTime.getMinutes() + fractionalPart(expirePolicy));
	       expireString = 'expires='+currentTime.toGMTString()+';';
		}
	}
	document.cookie = stateBagName+"="+cookieNewValue+";path=/;"+expireString;
  },
  get : function(cookieName,propName,expirePolicy){
	if(cookieName){
		expirePolicy = (!expirePolicy) ? '' : expirePolicy;
		var stateBagName = 'CookieStateBag_'+expirePolicy;
		var rg = new RegExp('(^|;\\s*)'+stateBagName+'=([^;]*)', 'ig');
		var pattern = rg.exec(document.cookie);
		if(pattern!=null){
			propName = BagProperties.getPropertyID(propName);
			var cookieNames = RegExp.$2.split("|");
			for(var i=0; i<cookieNames.length; i++){
				var a = cookieNames[i].split("#");
				if(a[0] == cookieName){
					if(a.length<2)
						break;
					var propVal = a[1].split('$');
					for(var j=0; j<propVal.length; j++){
						var v = propVal[j].split(":");
						if(v[0] == propName)
							return (v.length>1)?unescape(v[1]):"";
					}
				}
			}
		}
	}
	return null;
  }
}

 function fractionalPart(num){
   var sNumber = num.toString();
   var i = sNumber.indexOf('.');
   if(i == -1)
      return false;
   else
      return parseInt(sNumber.slice(i+1,sNumber.length)); 
 }

Array.prototype.contains = function(object) {
	for(var i = 0; i < this.length; i++) {
		if (object == this[i]) return true
	}

	return false
}

var editCharsRemain = Class.create();
editCharsRemain.prototype = {
	initialize: function(idField, params) {
		this.idField = idField;
		this.initError = false;
		this.timer = null;
		
		if(!this._checkField()) return;
		this.idHint = this._initHintId(params);
		this.maxLength = this._initMaxLength(params);
		this.messageTemplate = this._initMessageTemplate(params);
		this.messageLimitTemplate = this._initMessageLimitTemplate(params);
		
		if(!this.initError) this.bind();
	},
	_checkField: function() {
		var field = $(this.idField);
		if(!field) return false;
		return true;
	},
	_initHintId: function(params) {
		if(params && params.hintId) {
			if($(params.hintId)) return params.hintId;
		}
		this.initError = true;
	},
	_initMaxLength: function(params) {
		if(params && params.maxLength && parseInt(params.maxLength) > 0) {
			return params.maxLength;
		}
		this.initError = true;
	},
	_initMessageTemplate: function(params) {
			if(params && params.messageTemplate != undefined ) {
				return params.messageTemplate;
			}
			return '<b>#{charsRemain}</b> characters remaining';
	},
	_initMessageLimitTemplate: function(params) {
			if(params && params.messageLimitTemplate != undefined ) {
				return params.messageLimitTemplate;
			}
		return '<span style="color: red">Size limit reached. Please shorten your message.</span>';
	},
	bind: function() {
		["change", "keydown", "keyup", "keypress", "paste"].each(function(event) {
			Event.observe(this.idField,event, this._fieldChangeHandler.bindAsEventListener(this));
		}.bind(this));
		
		Event.observe(this.idField, 'focus', this._startTimer.bind(this));
		Event.observe(this.idField, 'blur', this._stopTimer.bind(this));
		
		this._fieldChangeHandler();
	},
	
	_fieldChangeHandler: function(e) {
		var field = $(this.idField);
		var charsRemain = this.maxLength - this._fieldLength();

		var templateParams = {'charsRemain': charsRemain };
		var template = new Template( charsRemain <= 0 ? this.messageLimitTemplate : this.messageTemplate);
		this._showHintMessage(template.evaluate(templateParams));
		if (charsRemain <= 0) {
			if(e && !this._isEditKeys(e.keyCode)) e.stop();
			if( charsRemain < 0 ) field.value = field.value.substring(0, this.maxLength);
		}
	},
	
	_isEditKeys: function(keyCode) {
		return [8, 9, 27, 33, 34, 35, 36, 37, 38, 39, 40, 45, 46].indexOf(keyCode) != -1; 
	},
	
	_fieldLength: function() {
		return $(this.idField).value.length
	},

	_showHintMessage: function(msg) {
		$(this.idHint).update(msg);
	},
	
	_startTimer: function() {
		if(this.timer) return;
		this.timer = new Form.Element.Observer(
			$(this.idField),
			0.2,
			function(el, value){ this._fieldChangeHandler(); }.bind(this)
		);
	},
	
	_stopTimer: function() {
		if(this.timer) this.timer.stop();
		this.timer = null;
	}
};


Object.extend(editCharsRemain, {
	items: [],
	add: function(idField, params) {
		var item = new editCharsRemain(idField, params);
		if(!item.initError) this.items.push();
	}
});

var changeFieldNotify = Class.create();
changeFieldNotify.prototype = {
	initialize: function(idNotify, groupClass) {
		this.elNotify = $(idNotify);
		this.initError = false;
		if(!this.elNotify) {
			this.initError = true;
			return;
		}
		
		this.groupClass = groupClass;

		this.initError = false;
		this.timer = null;
		this.savedElements = null;
		this.savedValuesHash = '';
		
		this.selectRule = 'INPUT.' + this.groupClass + ', .' + this.groupClass + ' INPUT,';
		this.selectRule += 'TEXTAREA.' + this.groupClass + ', .' + this.groupClass + ' TEXTAREA,';
		this.selectRule += 'SELECT.' + this.groupClass + ', .' + this.groupClass + ' SELECT';

		$$(this.selectRule).each( (function(el){
			this._bindElement(el);
		}).bind(this) );
		
		this.saveElementsState();
	},
	
	_bindElement: function(el) {
		var isSelectElement = (el.tagName == 'SELECT');
		var eventList =
			isSelectElement
			? ["change"]
			: ["change", "keydown", "keyup", "keypress", "paste"];
			
		eventList.each(function(event) {
			Event.observe(el, event, this._elementChangeHandler.bindAsEventListener(this));
		} .bind(this));

		if( !isSelectElement ) {
			Event.observe(el, 'focus', this._startTimer.bind(this, el));
			Event.observe(el, 'blur', this._stopTimer.bind(this));
		}
	},

	_elementChangeHandler: function(e) {
		this.elNotify.style.display =
			(this.savedValuesHash == this._getValuesHash()) ? 'none' : 'block';
	},

	_startTimer: function(el) {
		if (this.timer) return;
		this.timer = new Form.Element.Observer(
			el,
			0.2,
			function(el) { this._elementChangeHandler(); } .bind(this)
		);
	},

	_stopTimer: function() {
		if (this.timer) this.timer.stop();
		this.timer = null;
	},
	
	saveElementsState: function() {
		this.savedElements = [];
		
		$$(this.selectRule).each( (function(el){
			this.savedElements.push(el);
		}).bind(this) );
		this.savedValuesHash = this._getValuesHash();
		this.elNotify.style.display = 'none';
	},
	
	_getValuesHash: function() {
		var hash = '';
		this.savedElements.each(function(el){
			var value = '';
			switch(el.tagName) {
				case 'INPUT':
					switch(el.type) {
						case 'checkbox':
							value = el.checked ? '1' : '0';
							break;
							
						case 'text':
						case 'hidden':
						case 'password':
						case 'file':
						case 'radio':
							value = $F(el);
							break;
							
						default:
							throw "Unsupported input element.";
					}
					break;
					
				case 'TEXTAREA':
				case 'SELECT':
					value = $F(el);
					break;
					
				default:
					throw "Unsupported element.";
			}
			hash += value + ',';
		});
		return hash;
	}
};

Object.extend(changeFieldNotify, {
	items: {},
	add: function(idNotify, groupClass) {
		var item = new changeFieldNotify(idNotify, groupClass);
		if (!item.initError) {
			this.items[groupClass] = item;
			return item;
		}
		return null;
	},

	save: function(groupClass) {
		var item = this.items[groupClass];
		if( item != undefined ) item.saveElementsState();
	}
});




// [AtlasScript]

if(typeof(Sys)!="undefined")
	Sys.Application.notifyScriptLoaded();

// [/AtlasScript]
			