/**
* Project js Library
*/ 
function parseHash(event){

	var result = portal.hash.parse();
	if (result['id'] || result['url']){
		
		// additional parameters for the popup
		var popupParams = {
			'invite-friend' : {'width' : 690, 'callback': function(){$('.b-lightbox-inner').append('<div class="ico-invite-friends"></div>')}},
			'clock' : {'width' : 920},
			'about' : {'width' : 750, 'title_class' : 'about'},
			'login' : {'width' : 700, 'close_text' : '', callback: function(){$('div.b-always-regs').after($('#l-ttl'))}},
			'register' : {'width' : 950, 'close_text' : '', callback: function(){
				$('div.b-always-regs').after($('#l-ttl'));
				// connect JS
				portal.script.load('/js/admin/adm_fields_controller-src.js');
				
				var initAjaxForms = function(){
					// connecting fields checker
					if (typeof FieldsController == 'undefined'){
						var FieldsController = new objAdminFieldsController();
					}
					
					if (typeof form_fields == 'undefined'){
						var form_fields = {};
					}
					
					form_fields['username'] = {
						'type' : 'text'
						,'onblur' : project.onformblur
						,'empty' : false
					};
			
					form_fields['password'] = {
						'type' : 'text',
						'maxlength' : 64,
						'minlength' : 6,
						'fullempty' : false,
						'fieldReg' : regular_str.password
						,'onblur' : project.onformblur
						,'empty' : false
										
					};
					form_fields['email'] = {
						'type' : 'text',
						'fieldReg' : regular_str.email
						,'onblur' : project.onformblur
						,'empty' : false
					};
					form_fields['captcha'] = {
						'type' : 'text'
						,'onblur' : project.onformblur
						,'empty' : false
					};
				
					form_fields['is_register_agree'] = {
						'type' : 'boolean'
						//,'onblur' : project.onformblur
						,'empty' : false
					};
				
					FieldsController.attach(form_fields,
						{'id': 'f-add-ads',
						'onchecksuccess' : project.oncheck,
						'oncheckfail' : project.oncheck/*,
						'onsubmit' : save_data*/}
					);
					
					//$('.niceCheck').live('click', function(){project.onformblur(FieldsController, 'is_register_agree', $_('is_register_agree').checked ? true : false)});
					
					$('#is_register_agree').unbind('change').bind('change', function(){
						//console.log($(this).is(':checked'));
						project.onformblur(FieldsController, 'is_register_agree', $(this).is(':checked'));
					});
					
					//FieldsController.checkForm();
				
				}
				syncEvent(function(){
					try {
						initAjaxForms();
					} catch(e){
						console.log(e);
					}
				}, 'typeof objAdminFieldsController!="undefined"');
		
				/*jQuery(".niceCheck").unbind('mousedown').mousedown(
					function() {
					    changeCheck(jQuery(this));
				});*/
				
			}},
			'all-tours' : {'height': 600, 'title_class' : 'h', 'correctHeight': false, callback: function(){$('.tours-list-up').click(function(){popup.destroy(popup)})}}
		};
		
		// try to find params for current page
		var params = null;
		if (result['url']){
			for (var i in popupParams){
				if (result['url'].indexOf(i) != -1){
					params = popupParams[i];
					break;
				}
			}
		}		
				
		if (typeof popup != 'undefined') 	
			popup.destroy(popup);

		popup = new oPopupLayer({'insert_callback' : function (popup){
			$(popup.getContent()).find('form').addClass('frmAjx');
			portal.ajax.attach_forms(popup);
			$('#l-content .close').click(function(){popup.destroy(popup)}); 
			//$('#l-content form').jNice();

			//reinitScrollPane();
			if (params && typeof params.callback == 'function'){
				params.callback();
			}
			}, 
			'window' : params,
			'doch' : getClientHeight()});
		popup.create();
		portal.ajax.load(null, result, popup.insert);
			
	} else if ('print' in result){
		// adding new element to footer
		$(document.body).append('<a class="b-print-link" href='+document.location.href.replace(/#.+/, '')+'">'+document.location.href.replace(/#.+/, '')+'</a>');
		$(document.body).append($('.copy'));
		portal.print();
	} else if ('comments' in result){	
		// parsing comments page - add some timeout
		if (typeof result['comments'] != 'undefined'){
			setTimeout("window['comments'][0].updPage('"+result['comments']+"')", 500);
		} else {
			$.scrollTo('#comments', 300);
		}
	} else {
		var fmid = null;
		for (var i in result){
			if ((fmid = /^oFMailer_(.*)/i.exec(i)) && typeof(oFMailer[fmid[1]]) == 'object'){
				addMailerClick($('.b-send-friend')[0], fmid[1]);
				break;
			} else if (/^faq-(.*)/i.test(i)){
				showFAQ(i);
			}
		}
	}

}



// we need global namespace
oFMailer = {};

function addMailerClick(object, index){
	// additional parameters for the popup
	var params = {'width' : 700};

	if (typeof popup != 'undefined') 	
		popup.destroy(popup);

	popup = new oPopupLayer({
		'insert_callback' : function (popup){
			$(popup.getContent()).find('form').addClass('frmAjx');
			//portal.ajax.attach_forms(popup);

			$('#l-content .close').click(function(){popup.destroy(popup)}); 
			/*if (params && typeof params.callback == 'function'){
				params.callback();
			}*/
		}, 
		'window' : params,
		'doch' : getClientHeight()});
	popup.create();

	params = {'callback' : popup.insert, 'container' : popup};
	if (object.getAttribute('sendhref')){
		params['sendhref'] = object.getAttribute('sendhref');
	}
	
	oFMailer[index].addParams(params);
	oFMailer[index].Load();

}



/** time boxes and news collapse **/
var tb_state = portal.storage.get('project_tb_state');
function openAll(state){
	
	if (typeof state == 'undefined' || state === null)
		state = tb_state;
		
	if (!state){
		//$('#b-collapse-all span').addClass('active');
		$('.time_items .news_a').each(function(){
			if ($(this).next().css('display') != 'block'){
				openNews(this);
			}
		});
			
		tb_state = true;
		$('#b-collapse-all i').html(portal.mess.collapse.collapse);
	} else {
		$('#b-collapse-all span').removeClass('active');
		$('.time_items .news_a').each(function(){
			if ($(this).next().css('display') == 'block'){
				openNews(this);
			}
		});

		tb_state = false;
		$('#b-collapse-all i').html(portal.mess.collapse.uncollapse);
	}
	
	portal.storage.set('project_tb_state', tb_state);

}


function tabs(mask, ind, cls)
{
  $('.'+cls).each(function(){
    if($(this).attr('id').indexOf(mask+'_') != -1) $(this).removeClass(cls);
  });
  $('#'+mask+'_'+ind).addClass(cls);
  $('.'+mask).each(function(){
    if($(this).attr('id').indexOf(mask+'_cont_') != -1) $(this).css('display','none');
  });
  $('#'+mask+'_cont_'+ind).css('display','block');
}



/** open close comments 
* @param string $state 
*/
function comments_open_close(state){

	// determine state
	if (typeof state == 'undefined'){
		if (!window['comments'][0].getOpenState())
			state = 'open'
		else
			state = 'close';			
	}
	
	switch (state){	
	case 'close':
		$('#close_comm').addClass('up');
		$('.art_com_block').slideUp('fast');
		portal.storage.set('project_comm_close', 1);
		//window['comments'][0].setOpenState(false);
		break;
		
	case 'open':	
	    $('.art_com_block').slideDown('fast');    
	    $('#close_comm').removeClass('up');    
	    portal.storage.set('project_comm_close', 0);
		//window['comments'][0].setOpenState(true);
		break;
	}

}


webt_store = {};
webt_store.buy = function(){

}


project = {};

project.vars = {};
var BUTTONS_STATE = {'ctrl': false};

project.switchLang = function(nick){
	var match = null, newloc = null;
	if (match = /^http:\/\/[^\/]+\/(?:([a-z]{2})\/)?([^?]*)(?:\?.*)?$/i.exec(window.location.href)){
		//console.log(match);
		if (typeof match[2] != 'undefined' && match[2]){
			newloc = '/'+nick+'/'+match[2];
		} else {
			newloc = '/'+nick+'/'+(typeof match[1] != 'undefined' ? match[1] : '');
		}
		window.location.href = newloc+'?'+(new Date().getTime());
		//console.log(newloc);
	}

}


project.showPopup = function (params){

	if (typeof params.mode != 'undefined' && typeof params.id != 'undefined' ){
		
		if (typeof popup == 'object')
			popup.destroy(popup);
		
		if (params.mode == 'map'){

			var aparams = {'width' : 515};
			popup = new oPopupLayer({'window' : aparams});
			popup.create();
		
			popup.insert(null, {'title' : $_('map-descr-'+params.id).innerHTML, 'content' : '<iframe width="420" frameborder="0" border="0" scrolling="no" height="270" align="center" id="map-popup-'+params.id+'" src="'+maps[params.id].href+'"></iframe>'});
			
		} else {
		
			popup = new oPopupLayer();
			popup.create();
			popup.insert(null, {'title' : typeof params.title != 'undefined' ? params.title : '', 'content' : $_(params.mode+'-'+params.id) ? $_(params.mode+'-'+params.id).innerHTML : ''});
		
		}

	}
	
}

/**
* method toggle blocks on main page
* @param state object of items with switchers 0 or 1
*/
project.mainSliderToggle = {
	
	// toggler count
	_cnt : 3,
	_opened : {},
	_prev_opened : {},
	_uploaded : {},
	_prefix : '',
	_section : '',
	_togglespeed : 300,
	_map : {'1' : 'top24', '2' : 'last', '3' : 'comments'},

	init : function(section, cnt, prefix){
	
		if (typeof section == 'undefined')
			this._section = 'mainSliderToggle';
		else
			this._section = section;
			
		if (typeof cnt != 'undefined')	
			this._cnt = parseInt(cnt);
			
		if (typeof prefix != 'undefined')
			this._prefix = prefix;
		else
			this._prefix = 'b-mstoggle-';
			
		var state = portal.storage.get('project.'+this._section);
		if (state && typeof state == 'object'){
			for (var i in state){
				//console.log(i+': '+parseInt(state[i]));
				this._opened[i] = parseInt(state[i]);
				this._chState(i, parseInt(state[i]), 0);
			}
			
		} else {
			state = {};
			var i = 1;
			while (i <= this._cnt){
				state[i] = 1;
				this._opened[i] = 1;
				i++;
			}
			portal.storage.set('project.'+this._section, state);

		}
		
		for (var i in this._opened)
			this._prev_opened[i] = this._opened[i];
		
		// update events on each toggler
		var i = 1;
		var athis = this;
		while (i <= this._cnt){
			$('#'+this._prefix+i).click(function(){project.mainSliderToggle.toggle($(this).attr('id').replace(athis._prefix, ''))});
			i++;
		}
		
		var i = 1;
		while (i < this._cnt){
			this._uploaded[i] = false;
			i++;
		}
		
		this.uploading();
	
	},
	
	_chState: function (num, state, togglespeed, force){

		var obj = $_(this._prefix+num);
		
		if (typeof state != 'undefined' && state == 1){
			portal.css.removeClass(obj, 'rolldown');
			portal.css.addClass(obj, 'rollup');
			obj.innerHTML = portal.mess.collapse.down;
			if ($_(this._prefix+'cnr-'+num).style.display == 'none' || (typeof force != 'undefined' && force))
				$('#'+this._prefix+'cnr-'+num).slideToggle(typeof togglespeed != 'undefined' ? togglespeed : this._togglespeed);
		} else {
			portal.css.removeClass(obj, 'rollup');
			portal.css.addClass(obj, 'rolldown');
			obj.innerHTML = portal.mess.collapse.up;
			$('#'+this._prefix+'cnr-'+num).slideToggle(typeof togglespeed != 'undefined' ? togglespeed : this._togglespeed);
		}
		
	},
	
	toggle : function(num){
	
		var state = portal.storage.get('project.'+this._section);
		if ($_(this._prefix+parseInt(num))){
			state[num] = state[num] == 1 ? 0 : 1;
			this._opened[num] = state[num];
			project.mainSliderToggle._chState(num, state[num]);
		}
	
		// checking for all closed
		var not_closed = 0;
		for (var i in state){
			//console.log(i+': '+state[i]);
			not_closed += state[i];
		}

		if (!not_closed && this._cnt != 1){
			state[1] = 1;
			project.mainSliderToggle._chState(1, state[1], this._togglespeed, true);
			this._opened[1] = 1;
		}
		portal.storage.set('project.'+this._section, state);
		
		this.uploading();
		
	},
	
	uploading: function(){
	
		// finding all new opened
		var cnt = 0;
		var prevcnt = 0;
		var changed = {};
		for (var i in this._opened){
			if (this._opened[i] == 1)
				cnt++;
			if (this._prev_opened[i] == 1)	
				prevcnt++;
				
			if (this._opened[i] == this._prev_opened[i])
				changed[i] = this._opened[i] - this._prev_opened[i];

		}
		
		//console.log(cnt, prevcnt);
		if (cnt == 3 && prevcnt < 3){
			// closeup all items
			for (var i in this._opened){
				
				this.load(i, 'closed');

			}
		}
		
		if (cnt < 3){
			// closeup all items
			for (var i in this._opened){
				//console.log(i, !this._uploaded[i]);
				if (this._opened[i] == 1 && !this._uploaded[i])
					this.load(i, 'opened');

			}
		}
		
		for (var i in this._opened)
			this._prev_opened[i] = this._opened[i];
	
	},
	
	load : function(i, state){
	
		var athis = this;
		project.ajax.get('main', function(response){$_('b-mstoggle-inner-'+(i)).innerHTML = response.response.content; athis._uploaded[i] = state != 'closed'}, {'post' : {'sub' : this._map[i], 'state' : state}});
		
	}

};


/** 
* init cusel fields
*/
project.initCusel = function(){

	var params = {
		changedEl: ".select",
		visRows: 5,
		scrollArrows: true
	}

	cuSel(params);
}

project.onformblur = function(forms, caller, state){
	
	project.oncheck(caller, state);
	// check the whole form
	if (forms.checkForm(null, {'onlycheck' : true})){
		if ($_('b-submit-button'))
			$_('b-submit-button').disabled = false;
	} else {
		if ($_('b-submit-button'))
			$_('b-submit-button').disabled = true;
	}
	
}


project.onEditUserCheck = function(caller, state, info){
	
	if (caller == 'new_password'){
		
		if (state){
			$_('b-password_check').style.display = 'block';
			$_('b-password_check').className = 'inp_ok';
			
		} else {
			$_('b-password_check').style.display = 'block';
			$_('b-password_check').className = 'inp_attention';
		}
	} else {
	
		project.oncheck(caller, state, info);
	}
}


project.init_qa = function(){

	var loadQA = function(e){
	
		var ticket = portal.loader.create($_('b-qa-content'), {'mode' : 'float'});

		var o_qa = {};

		o_qa.insert = function (e, data, callback){

			if (ticket) portal.loader.destroy(ticket);
			
			if (typeof data != 'undefined'){
				$('#b-qa-content').html(data.content);
				$('#b-qa-content').find('form').addClass('frmAjx');
				portal.ajax.attach_forms(o_qa);
				
				// checking for form height
				if ($('#b-qa-content .content-outer').height() > $('#b-qa-content').height()){
					var newh = $('#b-qa-content .content-outer').height()+110+'px';
					$('#b-qa-content').css('height', newh);
					$('#b-qa').css('height', newh);
				}

				portal.script.load('/js/admin/adm_fields_controller-src.js');
				
				var initAjaxForms = function(){
					// connecting fields checker
					if (typeof FieldsController == 'undefined'){
						var FieldsController = new objAdminFieldsController();
					}
					
					var form_fields = {};
					
					form_fields['captcha'] = {
						'type' : 'text',
						'empty' : false
					};

					form_fields['descr'] = {
						'type' : 'text',
						'maxlength' : 5000,
						'empty' : false
					};				
					form_fields['email'] = {
						'type' : 'text',
						'fieldReg' : regular_str.email,			
						'empty' : false,
						'maxlength' : 64
					};
				
					FieldsController.attach(form_fields,
						{'id': 'f-add-qa',
						'onchecksuccess' : project.oncheck,
						'oncheckfail' : project.oncheck/*,
						'onsubmit' : save_data*/}
					);
				}
				
				syncEvent(function(){
					try {
						initAjaxForms();
					} catch(e){
						console.log(e);
					}
				}, 'typeof objAdminFieldsController!="undefined"');
				
			}
			///portal.hash.clear();
			
		}		
		
		portal.ajax.load(null, {'url' : '/'+lang_nick+'/qa/ajx/1/smphr/1/', 'domain' : domain}, o_qa.insert);
		
		$('#b-qa').animate({
		    'left': '-10'
			}, 200, 'swing', function() {
		    	$('#btn-qa').unbind('click').click(function(e){
		    		$('#qa-close').trigger('click');
					e.preventDefault();
					e.stopPropagation();
		    	});
			}
		);		
		e.preventDefault();
		e.stopPropagation();
		
		return false;	
	
	};
	
	$('#btn-qa').click(loadQA);
	
	// bind close button
	$('#qa-close').unbind('click').bind('click', function(e){
		
		$('#b-qa').animate({
		    'left': '-600'
			}, 200, 'swing', function() {
				$('#btn-qa').unbind('click').click(loadQA);
				portal.hash.clear();
			}
		);
		
		e.preventDefault();
		e.stopPropagation();
	
	});
	
}



project.oncheck = function(caller, state, info){
	
	if ($_('l-'+caller) || $_('l-'+caller.replace('_check', ''))){
		$('#l-'+caller+', #l-'+caller.replace('_check', ''))[0].className = state ? 'inp_ok' : 'inp_attention';
	}
	
	// getting detailed info for field
	if (typeof info != 'undefined' && typeof info.detailed == 'object'){
		for (var i in info.detailed){
			if (info.detailed[i] === false && $_(caller+'-'+i+'-error')){
				$_(caller+'-'+i+'-error').style.display = 'block';
			} else if ($_(caller+'-'+i+'-error')){
				$_(caller+'-'+i+'-error').style.display = 'none';
			}
		}
	}
}


// call when form not allowed
project.oncheckresult = function(state, info){
	
	if (!state){
		// for comments
		if (typeof info['comment_descr'] != 'undefined' && info['comment_descr']){
			if (!info['comment_descr']['state']['detailed']['maxlength']){
				alert(portal.mess.comments.err_descr_minlength);
			} else {
				alert(portal.mess.comments.err_fields_empty);
			}
		}
	}

}


/**
* rating callback
*/
project.rating = {};
project.rating.callback = function (response){

	if (typeof response != 'undefined' && response.content){
		
		if ($_('b-main-rating-value')){
			$_('b-main-rating-value').innerHTML = (response.content.rating_abs > 0 ? '+' : '')+response.content.rating_abs;
		}
		
	}

}


/** 
* favorites update 
*/
project.favotires = {};

project.favotires.init = function(what){
	if ($_(what)){
		project.favotires.get(what);
		$('#'+what).click(function(){
			project.favotires.set(what);
		});
	}	
}

project.favotires.update = function(response){

	if (typeof response == 'undefined' || !response.response.section) return false;

	// after update
	switch (response.response.section){
	
	case 'pg_catalog':
		if ($_('catalog-liked') && parseInt(response.response.status) == 2){
			$('#catalog-liked').hasClass('active') ? $('#catalog-liked').removeClass('active') : $('#catalog-liked').addClass('active');
		} else if ($_('catalog-liked') && parseInt(response.response.status) == 1){
			$('#catalog-liked').addClass('active');
		} else
			$('#catalog-liked').removeClass('active');
		
		break;

	case 'users':
		if ($_('users-liked') && parseInt(response.response.status) == 2){
			if ($('#users-liked').hasClass('active')){
				
				$('#users-liked').removeClass('active');
				$('#users-liked').html(portal.mess.like.add);
			
			} else {
			
				$('#users-liked').addClass('active')
				$('#users-liked').html(portal.mess.like.remove);
			
			};
		} else if ($_('users-liked') && parseInt(response.response.status) == 1){
			$('#users-liked').addClass('active');
			$('#users-liked').html(portal.mess.like.remove);
			
		} else {
			$('#users-liked').removeClass('active');
			$('#users-liked').html(portal.mess.like.add);
		}
		break;
	
	}
	
	
}

project.favotires.set = function(what){
	
	if ($_(what)){
	
		var elem_id = project.data.get(what, 'id');
		var section = project.data.get(what, 'section');
		project.ajax.get('portfolio', project.favotires.update, {'post' : {'elem_id' : elem_id, 'section' : section, 'update': 1}});
		
	}
}

project.favotires.get = function(what){
	
	if ($_(what)){
	
		var elem_id = project.data.get(what, 'id');
		var section = project.data.get(what, 'section');
		
		project.ajax.get('portfolio', project.favotires.update, {'post' : {'elem_id' : elem_id, 'section' : section}});
		
	}
}

/**
* data methods
*/
project.data = {
	'get' : function(elem_id, attr){

		var elem_id = $_(elem_id);
		if (elem_id){
			if (typeof attr != 'undefined'){
				return elem_id.getAttribute('data-'+attr);
			}
			
			var data = {};
			var reg = /^data-(.*)$/;
			var mt = null;
			
			for (var attr, i=0, attrs=elem_id.attributes, l=attrs.length; i<l; i++){
			    attr = attrs.item(i);
			    if ((mt = reg.exec(attr.nodeName)))
			    	data[mt[i]] = attr.nodeValue;
			}
			
			return data;
		}
	}, 
	
	'set' : function(elem_id, attr, value){

		var elem_id = $_(elem_id);
		if (elem_id){
			if (typeof attr != 'undefined'){
				return elem_id.setAttribute('data-'+attr, value);
			}
		}
	}
}

/**
* project AJAX interface
*/
project.ajax = {

	_ajx_href : '/ajax.php?resource=',

	get: function(method, callback, params){
	
		var athis = this;
		
		var req = new JsHttpRequest();
		req.onreadystatechange = function (){
			if (req.readyState == 4){
			
				callback(req.responseJS);	
				
			}
		};
		
		var query = athis._ajx_href+method;
		var send_object = null;
		if (typeof params != 'undefined' && typeof params.post != 'undefined'){
			send_object = params.post;
		} else if (typeof params != 'undefined' && typeof params.get != 'undefined'){
			for (var i in params.get){
				query += '&'+i+'='+	params.get[i];
			}
			//send_object = params.get;
		}
		
		req.open(typeof params != 'undefined' && typeof params.post != 'undefined' ? 'POST' : 'GET', query, true);
		req.send(send_object);
	
	}

};


/**
* comments 
* calling when comments loaded
*/
project.comments = {};

project.comments.scrollTo = function(e, id){
	if ($_('comments-'+id)){
		$.scrollTo('#comments-'+id, 300);
	}
	if (e){
		portal.events.stop(e);
	}
}

project.comments.postLoad = function(comments, response){

	// try to find all croppers
	if ($('.b-crop-anchor').length > 0){
		
		$('.b-crop-anchor').unbind('click').bind('click', function(){
			
			// setting cropper
			var athis = this;
			project.cropper.init({'callback' : function(){

				var crop = project.data.get(athis, 'crop');
				//console.log(crop);
				if (crop){
					
					crop = crop.split(';');
					// getting image dims
					var dims = project.data.get($_('g-main-photo'), 'dims').split(';');
					///console.log(dims);
					
					// now we have jcrop_api
					project.cropper.api.setSelect([parseInt(dims[0]) - parseFloat(crop[0])*parseInt(dims[0]), parseInt(dims[1])-parseFloat(crop[1])*parseInt(dims[1]), parseInt(dims[0])-parseFloat(crop[2])*parseInt(dims[0]), parseInt(dims[1])-parseFloat(crop[3])*parseInt(dims[1])]);
					project.cropper.api.disable();
					
					// scrolling!
					$.scrollTo(parseInt($('.jcrop-tracker:first').offset().top - 100 + 'px'), '300');
				}			
			
			}});
			
		});
				
	}

}

/**
* project voting
*/
project.voting = {};

project.voting.send = function(e, href, id){
	// sending form to the voting
	if (typeof id != 'undefined' && $_('voting_result_'+id)){
		
		var ticket = portal.loader.create($_('voting_result_'+id), {'mode' : 'float'});

		var athis = this;
		
		var req = new JsHttpRequest();
		req.onreadystatechange = function (){
			if (req.readyState == 4){
				if (ticket)
					portal.loader.destroy(ticket);
			
				$_('vote-'+id).innerHTML = req.responseJS.response;
				
			}
		};
		
		var query = '/ajax.php?resource=content';///href+'ajx/1';
		
		req.open('POST', query, true);
		var ans_id = 'answer_'+id;
		//console.log($('#voting_result_'+id+' input:checked').length);

		var domain = /http:\/\/([^\/]+)/.exec(href);
		var url = /^http:\/\/[^\/]+(\/.*)$/.exec(href);

		var post = {
				'params' : {
					'method' : 'post', 
					'domain' : domain[1], 
					'url' : url[1]+'ajx/1', 
					'lang_id' : lang_id},
				'ans_id' : $_('answer_'+id).value, 
				'ch_elem' : {
					'answer' : $('#voting_result_'+id+' input:checked').val()
					}
				};
		//console.log(post);		
		req.send(post);
		
	}
	portal.events.stop(e);
	return false;	
}



project.voting.get = function(href, id){
	// sending form to the voting
	if (typeof id != 'undefined'){
		
		var ticket = portal.loader.create($_('voting_result_'+id), {'mode' : 'float'});

		var athis = this;
		
		var req = new JsHttpRequest();
		req.onreadystatechange = function (){
			if (req.readyState == 4){
				if (ticket)
					portal.loader.destroy(ticket);
			
				$_('vote-'+id).innerHTML = req.responseJS.response;
				
			}
		};
		
		var query = '/ajax.php?resource=content';///href+'ajx/1';
		
		req.open('POST', query, true);

		var domain = /http:\/\/([^\/]+)/.exec(href);
		var url = /^http:\/\/[^\/]+(\/.*)$/.exec(href);

		var post = {
				'params' : {
					'method' : 'get', 
					'domain' : domain[1], 
					'url' : url[1]+'ajx/1', 
					'lang_id' : lang_id}
				};
		req.send(post);
	}
	return false;	
}



/** 
* pages initialzator
*/
project.init_pages = {};

project.vars.jcropset = false;
project.cropper = {

	_callback : null,	
	
	api: null,

	init : function(params){
	
		if (typeof params == 'undefined'){
			params = {};
		}
	
		var athis = this;
		releaseCheck = function (c){
			//console.log(c);
			$('#crop').val(JSON.stringify(c));
		};
		
		var onRelease = function(c){
			//console.log(project.cropper.api);
			project.cropper.api.destroy();
		}
		
		var onDoubleClick = function(c){
			
			if ($_('frmCommentAdd')){
				// insert dims to the commetns field
				var dims = project.data.get($_('g-main-photo'), 'dims').split(';');
				for (var i in dims)
					dims[i] = parseInt(dims[i]);
				
				var coords = [
					((dims[0]-c.x)/dims[0]).toPrecision(3),
					((dims[1]-c.y)/dims[1]).toPrecision(3),
					((dims[0]-c.x2)/dims[0]).toPrecision(3),
					((dims[1]-c.y2)/dims[1]).toPrecision(3)
					];
				$('#frmCommentAdd textarea').replaceSelection('[CROP]'+coords.join(';')+';[/CROP]');
				$.scrollTo('#frmCommentAdd textarea', 350);
				$('#frmCommentAdd textarea').focus();
				
			} else if ($_('upload-picture')){
			// update croper image
				
				var dims = project.data.get($_('upload-picture'), 'dims');
				dims = dims.split(';');
				
				// getting min dim
				var mindim = dims[0] > dims[1] ? dims[1] : dims[0];
 				
				var curr_sel = project.cropper.api.tellSelect();
				var sel = [];
				if (mindim == dims[0]){
					sel[0] = 0;
					sel[1] = parseInt(curr_sel['y'] + (curr_sel['y2']-curr_sel['y'])/2 - dims[1]/2);
					sel[2] = dims[0];
					sel[3] = parseInt(curr_sel['y'] + (curr_sel['y2']-curr_sel['y'])/2 + dims[1]/2);
				} else {
					sel[0] = parseInt(curr_sel['x'] + (curr_sel['x2']-curr_sel['x'])/2 - dims[0]/2);
					sel[1] = 0;
					sel[2] = parseInt(curr_sel['x'] + (curr_sel['x2']-curr_sel['x'])/2 + dims[0]/2);
					sel[3] = dims[0];
				}
				project.cropper.api.setSelect(sel);
			
			}
		}

	 	if (project.vars.jcropset && typeof project.cropper.api != 'undefined' && project.cropper.api){
	 		project.cropper.api.destroy();
	 		athis._callback = null;
	 	}
		
		if (typeof params != 'undefined' && typeof params.callback == 'function'){
			this._callback = params.callback;
		}
	 	
	 	// getting main image
	 	if (typeof params != 'undefined' && typeof params.container != 'undefined')
	 		var container = params.container;
	 	else
	 		var container = '#g-main-photo';

		var setup = {
            onChange: releaseCheck,
            onSelect : releaseCheck,
            onDblClick : onDoubleClick,
            onRelease : onRelease
          };
		
		if (typeof params.aspectRatio != 'undefined'){
			setup.aspectRatio = params.aspectRatio;
		}
		if (typeof params.minSize != 'undefined'){
			setup.minSize = params.minSize;
		}
		if (typeof params.maxSize != 'undefined'){
			setup.maxSize = params.maxSize;
		}
		
		$(container).Jcrop(setup, function(){
          	//console.log('init!');
			athis.api = this;
			//athis.api.enable();
			if (athis._callback != null){
				athis._callback(athis);
			}
			
			//athis.api.animateTo([100,100,400,300]);
		});
		project.vars.jcropset = true;
		/*} else {
				if (athis._callback != null){
					athis._callback(athis);
				}
		}*/
	}
};

/**
* catalog item page
*/
project.init_pages.catalog_item = function(){

	project.favotires.init('catalog-liked');
	
	$('.del-photo').bind('click', function() {
		$('#popup_del_album').show();
		el = $(this);
		
		$('#popup_del_album .yes').unbind('click');
		$('#popup_del_album .yes').bind('click', function () {
			location.href = el.attr('href');
		});
		$('#popup_del_album .no').unbind('click');
		$('#popup_del_album .no').bind('click', function () {
			$('#popup_del_album').hide();
		});
		
		return false;
	});
	
	$('.code_text').click(function(e){selectText(this); e.stopPropagation(); e.preventDefault();});
	$(window).bind('keydown', function(e){
		if (e.keyCode == 17){
			BUTTONS_STATE['ctrl'] = true;
		}
	});
	
	// turn off html code block (because ScrollPane work not good)
	$('div.code_drop_block').css('display', 'none');
	$('div.btn_kod b, div.btn_kod2 b').click(function(){
		$('div.code_drop_block').css('left', 'auto').css('right', '1px').slideToggle(200);
	});

	$(window).bind('keyup', function(e){
		if (e.keyCode == 37 && BUTTONS_STATE['ctrl'] && $('.photo_prev').length > 0){
			document.location.href = $('.photo_prev').attr('href');
		}
		if (e.keyCode == 39 && BUTTONS_STATE['ctrl'] && $('.photo_next').length > 0){
			document.location.href = $('.photo_next').attr('href');
		}
		if (e.keyCode == 17 && BUTTONS_STATE['ctrl']){
			BUTTONS_STATE['ctrl'] = false;
		}
		
	});
	
	// add hover methods on prev next
	var comm_img_cont = null;
	$('.photo_prev, .photo_next').bind('mouseenter', function(e){
		if ($(this).attr('rel') != ''){
			if (!comm_img_cont){
				comm_img_cont = $('<div/>').addClass('b-comm-img-cont');
				comm_img_cont.append($('<img/>'));
				comm_img_cont.appendTo($('body'));
			}
			comm_img_cont.css('display', 'block').css('left', e.pageX + 10 + 'px').css('top', e.pageY + 10 + 'px');
			comm_img_cont.find('img').attr('src', $(this).attr('rel'));
		}
	});
	
	$('.photo_prev, .photo_next').bind('mouseout', function(e){
		if (comm_img_cont)
			comm_img_cont.css('display', 'none');
	});
	
	
	if ($_('btn_crop')){

	 	$('#btn_crop').click(function(){
	 	
	 		project.cropper.init();
	 		
		});
	}

	// connect full screen page
	$('#btn_fullscreen, #g-main-photo').bind('click', function() {
		$('#b-qa').css('display', 'none');
		$.colorbox({
			width: "100%",
			inline: true,
			opacity: 100,
			href: ".photo_block_full",
			'onClosed' : function(){$('#b-qa').css('display', 'block');}
		});
	});

	$('.photo_block_full img').bind('click', function() {
		$.colorbox.close();
	});
	
	// color changer
	$('.photoline .color').bind('click', function() {
		var color = $(this).attr('href');
		$('.photo_block').css('backgroundColor', color);
		$('.photo_block1 h1').css('color', project.colors.getInverse(color));
		return false;
	});
	$('.photo_block_full .color').bind('click', function() {
		var color = $(this).attr('href');
		$('#cboxOverlay').css('backgroundColor', color);
		return false;
	});
	
	if($('#exif .descr_table td').length < 2) {
		$('#exif .descr_table').hide();
		$('#exif .nodata').show();
	}
	
	$('.photo_block1 h1').css('color', project.colors.getInverse($('.photo_block').css('backgroundColor')));
}




/**
* profile page
*/
project.init_pages.profile = function(){

	
	$('#b-get-in-fav-users, #b-get-fav-users').click(function(e){
	
		// try to find params for current page
		//console.log(/\/pid\/(\d+)/.exec(document.location.href));
		var arr = /\/pid\/(\d+)/.exec(document.location.href)
		
		var query = {'url' : '/'+lang_nick+'/fav-users/ajx/1/who/'+$(this).attr('id').replace('b-get-', '')+'/'};

		if (arr && arr[1]){
			query['url'] += 'pid/'+arr[1]+'/';
		}
		
		var ticket = portal.loader.create(document.body, {'mode' : 'float'});
		
		if ($_('drop_block_favorite')){
			$('#drop_block_favorite').remove();		
		}
		
		var _insert = function (e, data, callback){
			if (ticket) portal.loader.destroy(ticket);
			if (typeof data != 'undefined'){
				$(document.body).append(data.content);
				// reposition
				
				//$_('drop_block_favorite').style.position = 'fixed';
				$_('drop_block_favorite').style.top = parseInt($(document.body).scrollTop()) + 100 + 'px';
				$_('drop_block_favorite').style.left = ($(document.body).width() - parseInt($_('drop_block_favorite').offsetWidth))/2 + 'px';
				$('#btn-fav-close').unbind('click').bind('click', function (){$('#drop_block_favorite').remove()});

				// connect scroll pane
				$('#drop_block_favorite .scroll-pane').jScrollPane({showArrows:true,  dragMaxHeight: 5, scrollbarMargin: 0, scrollbarWidth : 22});								
			}
			portal.hash.clear();		
		}		
		
		portal.ajax.load(null, query, _insert);
				
		
		e.preventDefault();
		e.stopPropagation();
		
		return false;
		
	});
	
	
}


/**
* user profile editor
*/
project.init_pages.user_add = function(){

	$('#tel_plus').click(function(){
	
		var cloned = $('#b-phone-base').clone();
		
		cloned.attr('id', '').find('#tel_plus').remove();
		/*// update cusel
		var cuseld = cloned.find('div.cusel');
		cuseld.attr('id', 'cuselFrame-sel_photograf_'+newid)
		cuseld.find('div.cusel-scroll-pane').attr('id', 'cusel-scroll-sel_photograf_'+newid);
		cuseld.find('input').attr('id', 'sel_photograf_'+newid).attr('name', 'participant_type['+newid+']');
*/
		// update text value
		/*cloned.find('input.participant-inp').removeClass('example').attr('id', 'participant_'+newid).attr('name', 'participant['+newid+']').attr('disabled', 'disabled').attr('real_id', participants_temp_id);
				
		cloned.find('td:eq(1)').append(del_btn); */
		$('#b-phone-base').after(cloned);
		//del_btn.bind('click', function(){$(this).parent().parent().remove(); init_participants();});
		
	});
	
	$('#delete-profile').attr('p-href', $('#delete-profile').attr('href')).attr('href', '#').click(function(e){
		
		if (confirm(portal.mess.project.delete_profile)){
			document.location.href = $(this).attr('p-href');
		}
		
		e.preventDefault();
		e.stopPropagation();
		
		return false;
		
	});
	
	
	// connect autocompleter to the participants
	var ac_apply_event = false;
	var ac_apply_callback = function(ac, params) {
		$('#city_raw').val(params.value);
		if (typeof params.event != 'undefined'){
			portal.events.stop(params.event);
		}
	}
	
	var autocomp_callback = function(query){
		
		query['ch_elem[q]'] = $('#city_raw').val();
		return query;
	}

	var ac_city = new objAutocompleter({
		"objid" : "city_raw", 
		"loader_show" : false,
		'checkTout' : 200,
		'minchars' : 2,
		'nowait' : true,
		'width' : 281,
		'left_offset' : 0,
		"ajxhref" : "/ajax.php?resource=city&lang_id="+lang_id, 
		"callbacks" : {'before' : autocomp_callback, "apply" : ac_apply_callback}
		});	
	

	// check if we have uploader button
	if ($_('file-uploader')){
	
		// connect image uploader
		portal.script.load('/js/ajxFileUploader/fileuploader.js');
		portal.css.load('/js/ajxFileUploader/fileuploader.css');
		
		var callbackImage = function(id, file, resp){
		
			if(resp.file) {
			
				$('#upload-picture').attr('src', resp.file);

				if (typeof resp.info != 'undefined'){
				
					$_('b-filename').innerHTML = file;
					
					// resizing image to the maximum
					var max_width = 202;
					var dims = {};
					if (parseInt(resp.info['0']) <= max_width){
						dims['width'] = resp.info['0'];
						dims['height'] = resp.info['1'];
					} else {
						dims['width'] = max_width;
						dims['height'] = max_width*parseInt(resp.info['1'])/parseInt(resp.info['0']);
					}
					
					project.data.set($_('upload-picture'), 'dims', dims['width'] +';'+dims['height']);
					//$('#upload-picture').attr('height', parseInt($('#upload-picture').attr('width'))/parseInt(resp.info['0'])*parseInt(resp.info['1']));
					$('#upload-picture').attr('height', dims['height']).attr('width', dims['width']);
					
				}
				
				//$('.profile_pic').append(html);
				//project.bindDelImages();
			}else if(resp.error) {
				alert(resp.error);
			}
		}
		
		var init_uploader = function() {
			var ticket = null;
			var uploader = new qq.FileUploader({
				// pass the dom node (ex. $(selector)[0] for jQuery users)
				element: $('#file-uploader')[0],
				// path to server-side upload script
				action: '/ajax.php?resource=upload&method=save_profile',
				// event
				onComplete: function (id, fileName, responseJSON){
					if (ticket)
						portal.loader.destroy(ticket);
	
					callbackImage(id, fileName, responseJSON);
				},
				onSubmit: function (id, fileName) {
					ticket = portal.loader.create('b-picture-form', {'mode' : 'float'});	
				},
				allowedExtensions: ['jpg','jpeg','png','gif']
			});
			
			$('.a-new-prev').bind('click', function() {
				$('.qq-upload-button input').trigger('click');
				return false;
			});
		};
		
		syncEvent(function(){init_uploader();}, 'typeof qq != "undefined"');	
		
	}

}

/**
* pm add page
*/

project.init_pages.pm_add = function() {
	$('.showhide').bind('click', function() {
		var id = $(this).attr('id').replace('b-', '');
		if(!$('#'+id).hasClass('lfdisplay')) {
			$('#'+id).show();
			$('#'+id).addClass('lfdisplay');
		}else{
			$('#'+id).hide();
			$('#'+id).removeClass('lfdisplay');
		}
	});	
	
	$('.list_favor1_inner a.ajx').bind('click', function() {
		$('#to_user_id_name').val($(this).text());
		$('#to_user_id').val($(this).attr('data-uid'));
		$('.showhide').click();
		return false;
	});

	// connect autocompleter to the participants
	var ac_apply_event = false;
	var ac_apply_callback = function(ac, params) {
		$('#to_user_id_name').val(params.value);
		if (typeof params.event != 'undefined'){
			portal.events.stop(params.event);
		}
	}
	
	var autocomp_callback = function(query){
		
		query['ch_elem[q]'] = $('#to_user_id_name').val();
		query['ch_elem[filters]'] = "users";
		return query;
	}

	var ac_participants = new objAutocompleter({
		"objid" : "to_user_id_name", 
		"loader_show" : false,
		'checkTout' : 200,
		'minchars' : 2,
		'nowait' : true,
		'width' : 174,
		'left_offset' : 0,
		"ajxhref" : "/ajax.php?resource=ac&lang_id="+lang_id, 
		"callbacks" : {'before' : autocomp_callback, "apply" : ac_apply_callback}
		});
	
	$('#to_user_id_name').bind('keydown', function(e){
	
		if (e.keyCode == 13 || e.keyCode == 3){
			e.preventDefault();
			e.stopPropagation();
			ac_apply_event = true;
			return false;
		}
	
	});	

	// connect autocompleter to the tags
	var tobj = $('#tags').fcbkcomplete({
        json_url: "/ajax.php?resource=ac_tags&lang_id="+lang_id,
        addontab: true,                   
        maxitems: 20,
        filter_case : false,
        firstletter : true,
        //showallbutton : true,
        height: 150,
        zIndex : 1000000,
        //cache: true,
        newel: true
    });
    
   
    /*if($('#title').val() != '' && $('#tags option').length == 0) {
    	$('#tags').next().addClass('inputbad');
    }*/
}

/**
* pm box
*/
project.init_pages.pm_box = function(){
	// checkbox
	$('.form_param a').bind('click', function() {
		var type = $(this).attr('href').replace('#', '');
		$('.check').each(function() {
			if(type == 'all' && !$(this).find('input').attr('checked')) {
				//alert('go');
				$(this).find('input').attr('checked', 'checked');
				//$(this).trigger('mousedown')
			}
			if(type == 'nothing' && $(this).find('input').attr('checked')) {
				//$(this).trigger('mousedown')
				$(this).find('input').attr('checked', false);
				
			}
			if(type == 'invert') {
				$(this).find('input').trigger('click');
			}
		});
		
		return false;
	});
}

/**
* catalog item page
*/
project.init_pages.photo_add_category = function(e) {
	var category = parseInt($(e).val());

	if(project.cats[category].is_contest == '1') {
		$('#b-status').hide();
		$('input[name="ch_elem[status]"]:first').attr('checked', true);
		$('input[name="ch_elem[status]"]').parent().removeClass('radioChecked');
		$('input[name="ch_elem[status]"]:first').parent().addClass('radioChecked');
		$('#b-contest').slideDown();

		$('a[href="#contest"]').unbind('click');		
		$('a[href="#contest"]').bind('click', function () {
			popup = new oPopupLayer({
				'insert_callback': function(popup){
					$('#l-content .close').click(function(){popup.destroy(popup)}); 
				}, 
				'window' : {width: '900'},
				'doch' : getClientHeight()
			});
			popup.create();
			popup.insert(popup, {title: project.cats[category].title, content: project.cats[category].contest_rules});
			
			return false;
		});
	}else{
		$('#b-status').show();
		$('#b-contest').slideUp();

		$('a[href="#contest"]').unbind('click');
	}
}

project.init_pages.photo_add = function(){
	$('#btn-add-album').bind('click', function() {
		if($(this).parent().find('.add_block_drop').css('display') == 'none') {
			$(this).parent().find('.add_block_drop').show();
		}else{
			$(this).parent().find('.add_block_drop').hide();
		}
	});
	
	// collect all participants
	var participants = {};
	var participants_temp_id = null;
	
	var init_participants = function(){
		participants = {};
		var par_tmp = [];
		//var i = 1;
		$('#participants-table').find('input.participant-inp').each(function(){
			if (!$(this).hasClass('example')){
				participants[$(this).attr('id').replace('participant_', '')] = $(this).data('id');//$(this).val();
				par_tmp[par_tmp.length] = $(this).attr('real_id');
				//i++;
			}
		});
		$('#participants_list').val(par_tmp.join(','));
	}
	
	init_participants();
	$('#participants-table a.delete').bind('click', function(){$(this).parent().parent().remove(); init_participants();});
		
	$('#btn-participant-add').click(function(){
		// getting next id for participant
		var newid = 0;
		for (var i in participants){
			if (parseInt(i) > newid){
				newid = i;
			}
		}
		newid++;
		//participants[newid] = '';
		
		var cloned = $('#participant-select-row').clone();
		var del_btn = $('<a />').attr('href', "javascript:void(0);").attr('class', "delete func_pad").html(portal.mess.forms.remove);
		cloned.attr('id', '').find('a').remove();
		// update cusel
		var cuseld = cloned.find('div.cusel');
		cuseld.attr('id', 'cuselFrame-sel_photograf_'+newid)
		cuseld.find('div.cusel-scroll-pane').attr('id', 'cusel-scroll-sel_photograf_'+newid);
		cuseld.find('input').attr('id', 'sel_photograf_'+newid).attr('name', 'participant_type['+newid+']');

		// update text value
		cloned.find('input.participant-inp').removeClass('example').attr('id', 'participant_'+newid).attr('name', 'participant['+newid+']').attr('disabled', 'disabled').attr('real_id', participants_temp_id);
				
		cloned.find('td:eq(1)').append(del_btn);
		$('#participant-select-row').before(cloned);
		del_btn.bind('click', function(){$(this).parent().parent().remove(); init_participants();});
		
		// now clear data in row
		//$('#participant_ac #participant_ac').val('');
		$('#participant_ac').val('');
		
		cuSelRefresh({'refreshEl' : '#sel_photograf_'+newid, 'visRows' : 5, 'checkZIndex' : true});
		
		init_participants();
		$('#participant_ac').val('');

	});
	
	$('#b-exif-del').click(function(){
		
		$('#exif_manufacturer, #exif_model, #exif_exposure, #exif_aperture, #exif_iso, #exif_focus, #exif_software').val('');
		
	});
	
	// connect autocompleter to the participants
	var ac_apply_event = false;
	var ac_apply_callback = function(ac, params) {
		$('#participant_ac').val(params.value);
		participants_temp_id = $('#'+params.id+' a').attr('href').replace(/^.*\/pid\/(\d+)\/$/i, '$1');
		if (ac_apply_event){
			$('#btn-participant-add').trigger('click');
		}
		if (typeof params.event != 'undefined'){
			portal.events.stop(params.event);
		}
	}
	
	var autocomp_callback = function(query){
		// saving name to the var
		participants_temp_id = $('#participant_ac').val();
		query['ch_elem[q]'] = $('#participant_ac').val();
		query['ch_elem[filters]'] = "users";
		return query;
	}

	var ac_participants = new objAutocompleter({
		"objid" : "participant_ac", 
		"loader_show" : false,
		'checkTout' : 200,
		'minchars' : 2,
		'nowait' : true,
		'width' : 174,
		'left_offset' : 0,
		"ajxhref" : "/ajax.php?resource=ac&lang_id="+lang_id, 
		"callbacks" : {'before' : autocomp_callback, "apply" : ac_apply_callback}
		});
	
	$('#participant_ac').bind('keydown', function(e){
	
		if (e.keyCode == 13 || e.keyCode == 3){
			e.preventDefault();
			e.stopPropagation();
			ac_apply_event = true;
			return false;
		}
	
	});

	// connect events on radio buttons
    $('#b-status .niceRadio').live("click", function(e) { 
    	if ($(this).find('input').attr('checked')){
    		if ($(this).find('input').attr('value') > 0){
    			$('#photo-modes').slideUp(200);
			} else {
    			$('#photo-modes').slideDown(200);
	    	}
    	}	
    });
	
	// connect autocompleter to the tags
	var tobj = $('#tags').fcbkcomplete({
        json_url: "/ajax.php?resource=ac_tags&lang_id="+lang_id,
        addontab: true,                   
        maxitems: 20,
        filter_case : false,
        firstletter : true,
        //showallbutton : true,
        height: 150,
        zIndex : 1000000,
        //cache: true,
        newel: true
    });
    
    /*if($('#title').val() != '' && $('#tags option').length == 0) {
    	$('#tags').next().addClass('inputbad');
    }*/
    
	$('#add_album a').bind('click', function() {
		var ttl = $(this).parent().find('.inp').val();
		
		if(ttl != '') {
			$.post(
				'/ajax.php?resource=addAlbum',
				{
					title: ttl
				},
				function(data) {
					var item = eval('('+data+')');

					if(item.title != '') {
						var newvalue = '<span value="'+item.id+'" class="cuselActive">'+item.title+'</span>';
						$("#cusel-scroll-album_id").append(newvalue);  
						
						cuSelRefresh({'refreshEl' : '#album_id', 'visRows' : 5});
						//$('#cusel-scroll-album_id')
						$('.b-album-id .cuselText').text(item.title);
						$('#album_id').val(item.id);
						/*$('#cusel-scroll-album_id span').each(function() {
							$(this).attr('selected','');
							$(this).removeClass('cuselActive');
						});						
						$('#cusel-scroll-album_id').append('<span value="'+item.id+'" selected="selected" class="cuselActive">'+item.title+'</span>');
						
						
						$('#cuselFrame-album_id').unbind('click');
						$('#cuselFrame-album_id').bind('click', function() {
							setTimeout(function() {
								$('#cuselFrame-album_id .cusel-scroll-wrap').hide();
							}, 100);
							return false;
						});*/
					}
					
					$('#btn-add-album').click();
				}
			);
		}

		return false;
	});
	
	$('.exif_del').bind('click', function() {
		$('.load_form input[type="text"]').each(function() {
			if($(this).attr('name').search('exif_') >= 0) {
				$(this).val('');
			}
		});
	});
	
	$('#b-photo-form').submit(function(){
	
		$('input.participant-inp').attr('disabled', false);
		return true;	
	});

	// check if we have uploader button
	// init cropper
	if ($_('file-uploader')){
	
		// connect image uploader
		portal.script.load('/js/ajxFileUploader/fileuploader.js');
		portal.css.load('/js/ajxFileUploader/fileuploader.css');
		
		var init_uploader = function() {
			var ticket = null;
			var uploader = new qq.FileUploader({
				// pass the dom node (ex. $(selector)[0] for jQuery users)
				element: $('#file-uploader')[0],
				// path to server-side upload script
				action: '/ajax.php?resource=upload',
				// event
				onComplete: function (id, fileName, responseJSON){
					if (ticket)
						portal.loader.destroy(ticket);

					project.addFormImage(id, fileName, responseJSON);
					
					if ($_('picture-url'))
						project.onformblur(window['FieldsController'], 'picture-url', true);
					
				},
				onSubmit: function (id, fileName) {
					ticket = portal.loader.create('b-photo-form', {'mode' : 'float'});	
					$('#upload-picture').attr('src', '/skin/img/share/0.gif');
				},
				allowedExtensions: ['jpg','jpeg','png','gif']
			});
			
			$('.a-new-prev').bind('click', function() {
				$('.qq-upload-button input').trigger('click');
				return false;
			});
		};
		
		syncEvent(function(){init_uploader();}, 'typeof qq != "undefined"');	
		
	}
	
	if($('.profile_pic .uploaded').length > 0) {
		project.cropper.init({
		'container' : $_('upload-picture'), 
		'aspectRatio' : 1, 
		'minSize' : [200, 200], 
		'callback' : function(){
	
			// getting image dims
			var dims = project.data.get($_('upload-picture'), 'dims').split(';');
	
			// now we have jcrop_api
			if($('#crop').val() != '') {
				var crop = eval('(' + $('#crop').val() + ')');
			}
			
			if(typeof crop != 'undefined') {
				project.cropper.api.setSelect([crop.x, crop.y, crop.w, crop.h]);
			}else{
				project.cropper.api.setSelect([0, 0, parseInt(dims[0]), parseInt(dims[1])]);
			}			
		}});
	}
}

project.init_pages.photos_list = function() {

	// del links
	var el;
	$('.del-photo').bind('click', function() {
		$('#popup_del_album').show();
		el = $(this);
		
		$('#popup_del_album .yes').unbind('click');
		$('#popup_del_album .yes').bind('click', function () {
			location.href = el.attr('href');
		});
		$('#popup_del_album .no').unbind('click');
		$('#popup_del_album .no').bind('click', function () {
			$('#popup_del_album').hide();
		});
		
		return false;
	});

	$('.del-album').bind('click', function() {
		$('#popup_del_album').show();
		el = $(this);
		
		$('#popup_del_album .yes').unbind('click');
		$('#popup_del_album .yes').bind('click', function () {
			$.get(
				'/ajax.php?resource=delAlbum',
				{
					id: el.attr('id').replace('d', '')
				},
				function(data) {
					location.href = location.pathname;
				}
			);
		});
		$('#popup_del_album .no').unbind('click');
		$('#popup_del_album .no').bind('click', function () {
			$('#popup_del_album').hide();
		});
		
		return false;
	});	

	$('.edit-album').bind('click', function() {
		var el = $(this);
		var title = prompt('', el.attr('title'));

		if(title) {
			$.get(
				'/ajax.php?resource=editAlbum',
				{
					id: el.attr('id').replace('e', ''),
					title: title
				},
				function(data) {
					location.href = location.href;
				}
			);
		}

		return false;
	});	

	setTimeout(function() {
		$('#cusel-scroll-sel_cat span').bind('click', function(){
			var v = $(this).attr('value');
			location.href = location.pathname + '?category=' + v;
		});
		$('#cusel-scroll-sel_album span').bind('click', function(){
			var v = $(this).attr('value');
			location.href = location.pathname + '?album=' + v;
		});
	}, 500);
}


project.addFormImage = function(id, file, resp) {
	if(resp.file) {
	
		// gettin EXIF info
		if (typeof resp.exif != 'undefined'){
			//console.log(resp.exif);
			if (typeof resp.exif.ApertureValue != 'undefined'){
				$_('exif_aperture').value = resp.exif.ApertureValue;
			}
			if (typeof resp.exif.ExposureTime != 'undefined'){
				$_('exif_exposure').value = resp.exif.ExposureTime;
			}
			if (typeof resp.exif.Model != 'undefined'){
				$_('exif_model').value = resp.exif.Model;
			}
			if (typeof resp.exif.Make != 'undefined'){
				$_('exif_manufacturer').value = resp.exif.Make;
			}
			if (typeof resp.exif.ISOSpeedRatings != 'undefined'){
				$_('exif_iso').value = resp.exif.ISOSpeedRatings;
			}
			if (typeof resp.exif.FocalLength != 'undefined'){
				$_('exif_focus').value = resp.exif.FocalLength;
			}
			if (typeof resp.exif.Software != 'undefined'){
				$_('exif_software').value = resp.exif.Software;
			}
		}
		
		if (typeof resp.info != 'undefined'){
			// resizing image to the maximum
			var max_width = 600;
			var dims = {};
			if (parseInt(resp.info['0']) <= max_width){
				dims['width'] = resp.info['0'];
				dims['height'] = resp.info['1'];
			} else {
				dims['width'] = max_width;
				dims['height'] = max_width*parseInt(resp.info['1'])/parseInt(resp.info['0']);
			}
			
			project.data.set($_('upload-picture'), 'dims', dims['width'] +';'+dims['height']);
			//$('#upload-picture').attr('height', parseInt($('#upload-picture').attr('width'))/parseInt(resp.info['0'])*parseInt(resp.info['1']));
			$('#upload-picture').attr('height', dims['height']).attr('width', dims['width']);
			
			$('#upload-picture').attr('src', resp.file);
			$('#picture-url').val(resp.file);
			
			project.cropper.init({
				'container' : $_('upload-picture'), 
				'aspectRatio' : 1, 
				'minSize' : [200, 200], 

				'callback' : function(){
		
					// getting image dims
					var dims = project.data.get($_('upload-picture'), 'dims').split(';');					
					project.cropper.api.setSelect([0, 0, parseInt(dims[0]), parseInt(dims[1])]);
					
			}});
		}
		
		//$('.profile_pic').append(html);
		//project.bindDelImages();
	}else if(resp.error) {
		alert(resp.error);
	}
}


/**
* function confirm closed category
*/
project.confirmClosedCat = function(cat_id, is_auth){

	if (typeof popup != 'undefined') 	
		popup.destroy(popup);

	popup = new oPopupLayer({
		'insert_callback' : function (popup){
			//$(popup.getContent()).find('form').addClass('frmAjx');
			//portal.ajax.attach_forms(popup);

			$('input.b-no-confirm-button').click(function(){popup.destroy(popup)}); 
			/*if (params && typeof params.callback == 'function'){
				params.callback();
			}*/
		},
		'destroy_callback' : function (popup){
			if ($('#closed_back_href').val() != ''){
				window.location.href = $('#closed_back_href').val();
			}
		},
		'window' : {'width' : 678},
		'doch' : getClientHeight()});
	popup.create();
	popup.insert(null, {'title' : '', 'content' : $_('b-closed-cat-text').innerHTML}, null);
	
}

/**
* function confirm minus rating
*/
project.confirmMinusRating = function(value, user_id){

	// try to find user comment 
	if ($('div.comment-user-'+user_id).length > 0){
		window['rating'][0].save(value, 'force');
		return true;
	}
	
	if (typeof popup != 'undefined') 	
		popup.destroy(popup);

	popup = new oPopupLayer({
		'insert_callback' : function (popup){

			$('#btn-confirm-minus-no').unbind('click').click(function(){popup.destroy(popup)}); 
			
			$('#btn-confirm-minus-ok').unbind('click').bind('click', function(){
				
				if (trim($('#confirmText').val()) != '' && $('#confirmText').val().length > 10){
					$('#frmCommentAdd textarea').val($('#confirmText').val());
					$('#frmCommentAdd input[type="submit"]').trigger('click');
					$('#btn-confirm-minus-no').trigger('click');
					window['rating'][0].save(value, 'force');
				} else 
					alert(portal.mess.comments.err_descr_minlength);
				
			});
			
		},
		'window' : {'width' : 678},
		'doch' : getClientHeight()});
	popup.create();
	popup.insert(null, {'title' : '', 'content' : portal.mess.project.confirm_minus.replace('[VALUE]', value)+'<textarea id="confirmText"></textarea><input type="button" value="'+portal.mess.project.confirm_ok+'" class="go" id="btn-confirm-minus-ok" /><input type="button" value="'+portal.mess.project.confirm_no+'" class="go" id="btn-confirm-minus-no" />'}, null);
	
}

/**
* colors mini library
*/
project.colors = {};
project.colors.getInverse = function(color){
	
	var toHex = function(n){
	 n = parseInt(n,10);
	 if (isNaN(n)) return "00";
	 n = Math.max(0,Math.min(n,255));
	 return "0123456789ABCDEF".charAt((n-n%16)/16)
	      + "0123456789ABCDEF".charAt(n%16);
	}

	var new_red,new_green,new_blue,colors = [],new_colors = [];
	var distance = 50;
	if (color.indexOf('rgb') >= 0){
		var colors = color.replace('rgb', '').replace('(', '').replace(')', '').split(' ').join('').split(',');
		
	} else {
		var cutHex = function(h){return (h.charAt(0)=="#") ? h.substring(1,7):h};
		var hexToR = function(h){return parseInt((cutHex(h)).substring(0,2),16)};
		var hexToG = function(h){return parseInt((cutHex(h)).substring(2,4),16)};
		var hexToB = function(h){return parseInt((cutHex(h)).substring(4,6),16)};
		
		colors[0] = hexToR(color);
		colors[1] = hexToG(color);
		colors[2] = hexToB(color);
	}
	new_colors[0] = 255 - colors[0];
    new_colors[1] = 255 - colors[1];
    new_colors[2] = 255 - colors[2];
	
    // checking for inverse
    var sum_range = 0;
    for (var i in new_colors){
    	sum_range += new_colors[i] - colors[i];
    }
    
    if (sum_range < distance){
	    for (var i in new_colors){
	    	new_colors[i] += distance;
	    }
    }
    for (var i in new_colors){
    	new_colors[i] = toHex(new_colors[i]);
    }
    
	//console.log(color + ' : ' + '#'+new_colors.join(''));    
	    
    return '#'+new_colors.join('');
}


/**
* on DOM ready
*/
project.pseudoArr = {};
project.pseudoReady = function(){

	// execute pseudo functions
	if (typeof pseudoArr != 'undefined' && pseudoArr != null)
		for(var i in pseudoArr) {
			pseudoArr[i]();
		}


	// connecting to the input fields events
	var fields_defaults = {'#search-q' : '',
		'#full_search_q' : '',
		'#subscribe_email' : '',
		'#qa_fio' : '',
		'#qa_email' : '',
		'#s-keys' : '',
		'#s-keys2' : '',
		'.b-faq-form #title': '',
		'.b-faq-form #email': '',
		'.b-faq-form #post': '',		
		'.b-faq-form #descr': '',
		'#city': '',
		'#q': ''
		};
	
	for (var i in fields_defaults){
		fields_defaults[i] = $(i).attr('value');
		$(i).attr('reg', i);
		$(i).bind('focus', function(){
			if ($(this).attr('value') == fields_defaults[$(this).attr('reg')])
				$(this).attr('value', '');
			});
		$(i).bind('blur', function(){
			if ($(this).attr('value') == '')
				$(this).attr('value', fields_defaults[$(this).attr('reg')]);
			});
	}
	
	var popup;
	
	/** main page toggler **/
	if ($_('b-mstoggle-1')){
		project.mainSliderToggle.init();
		
		// connect main page slider
		var comm_img_cont = null;
		$('#b-mstoggle-cnr-3 .img_cont').live('mouseenter', function(e){
			if ($(this).attr('rel') != ''){
				if (!comm_img_cont){
					comm_img_cont = $('<div/>').addClass('b-comm-img-cont');
					comm_img_cont.append($('<img/>'));
					comm_img_cont.appendTo($('body'));
				}
				comm_img_cont.css('display', 'block').css('left', e.pageX + 10 + 'px').css('top', e.pageY + 10 + 'px');
				comm_img_cont.find('img').attr('src', $(this).attr('rel'));
			}
		});
		
		$('#b-mstoggle-cnr-3 .img_cont').live('mouseout', function(e){
			comm_img_cont.css('display', 'none');
		});
		
	}
	
	/** profile slide toggle **/
	if ($_('b-fltoggle-1')){
		project.mainSliderToggle.init('profileSlider', 1, 'b-fltoggle-');
	}

	/** QA slider init **/
	if ($_('b-qa')){
		project.init_qa();
	}
	
	// adding listner to the calendar
	if ($('#b-cal-container').length > 0){
		var oCalendar = new ajxCalendar({'objID' : 'b-cal-container', 'ajxhref' : '/events/view/calendar/smphr/1/ajx/1/', 'elem' : '0', 'callback': function(){}});
		if (oCalendar) oCalendar.load();
	}		
	
	
	
	// init cusel
	project.initCusel();
	// connect scroll pane
	$('.scroll-pane').jScrollPane({showArrows:true,  dragMaxHeight: 5, scrollbarMargin: 0, scrollbarWidth : 22});
	

	/** comments **/
	if ($('.b-comm-add').length > 0){
		$('.b-comm-add').click(function(e){
			$.scrollTo('#add_comment_anchor', 300);
		});
	}
	


	
	/** auth **/
	if ($('.ajx').length > 0){
		$('.ajx').live('click', function (event){
	
			event.returnValue = false;
			event.preventDefault ? event.preventDefault() : '';
			
			if (typeof $(this).attr('p-href') == 'undefined')
				$(this).attr('p-href', $(this).attr('href')).attr('href', 'javascript:void(0);');
			
			portal.hash.set('#url='+$(this).attr('p-href')+'&redirect='+document.location.href);
			parseHash(event);
		});
	}	

	
	
	// connect events to subscribe block
	$('#f-subscribe').live('submit', function(e){
	
		event.returnValue = false;
		event.preventDefault ? event.preventDefault() : '';
		
		if (typeof $(this).attr('p-href') == 'undefined')
			$(this).attr('p-href', $(this).attr('action')).attr('action', 'javascript:void(0);');

		var ticket = portal.loader.create('b-subscribe', {'mode' : 'float'});

		var subscribe_insert = function (e, data, callback){
			if (ticket) portal.loader.destroy(ticket);
			if (typeof data != 'undefined'){
				$_('subscribe-container').style.display = 'block';
				$_('subscribe-container').innerHTML = data.content;
			}
			portal.hash.clear();		
		}		
		
		//portal.hash.set('#'+$(this).attr('p-href')+'ajx/1/email/'+$(this).find('.sub-email').val()+'/');
		var query = 'email/'+$(this).find('.sub-email').val()+'/';
		if ($_('sub_cat'))
			query += 'cat/' +$_('sub_cat').value+'/';
		if ($_('sub_cat_hash'))
			query += 'cat_hash/' +$_('sub_cat_hash').value+'/';
		//portal.debug.dump($(this).attr('p-href')+'ajx/1/'+query);
		portal.ajax.load(null, {'url' : $(this).attr('p-href')+'ajx/1/'+query}, subscribe_insert);

		/*if ($(this).find('.sub-email').val() == '' || !regulars['email'].test($(this).find('.sub-email').val())){
			alert(portal.mess.bad_email);
			e.preventDefault();
			return false;
		}*/
	});			
	
	
	// connect photo item
	if ($('#g-photo-item').length > 0){
		
		project.init_pages.catalog_item();

	}

	// connect photo add
	if ($('.load_form').length > 0){
		
		project.init_pages.photo_add();		

	}

	// connect photo add
	if ($('.photo-list').length > 0){
		
		project.init_pages.photos_list();		

	}
	
	// init profile page
	if ($('.profile_left').length > 0){
		
		project.init_pages.profile();		

	}
	
	// edit profile
	if ($('form.b-edit-profile-form').length > 0){
	
		project.init_pages.user_add();
		
	}

	// pm add
	if ($('form.message_form').length > 0){
	
		project.init_pages.pm_add();
		
	}

	// pm box
	if ($('form.form_message').length > 0){
	
		project.init_pages.pm_box();
		
	}
	
	// connect profile clip
	if ($_('users-liked')){
		
		project.favotires.init('users-liked');
		
	}
	
	// connect gallery
	if ($('#viewer').length > 0){
		$('#viewer').timerGallery({ easing : 'easeInOutCubic', opacity: '1', timer: true, interval: '7000'});
	}
	
	// adding listener to the search form
	/*if ($('#b-search-form').length > 0){
		$('#b-search-form').bind('submit', function(e){
			e.returnValue = true;
			//e.preventDefault ? e.preventDefault() : '';
			$('#b-search-form').attr('action', '/'+lang_nick+'/search/q/'+$(this).find("input[name='ch_elem[q]']").val());
			return e.returnValue;
		})
	}*/
	
	if ($('#b-search-form').length > 0){
		
		// connect autocompleter
		var ac_apply_callback = function(ac, params) {
		
			var new_href = '/'+lang_nick+'/search/q/'+$('#full_search_q').val()+'/filters/'+$_('sel_search').value+'/type/fast/';
			if (document.location.href.indexOf('tag/') >= 0){
				 var href_add = /^.*(tag\/[^\/]+\/).*$/.exec(document.location.href);
				 new_href += href_add[1];
			}
			//alert(new_href);
			document.location.href = new_href;
		}
		
		var autocomp_callback = function(query){
			if ($_('sel_search')){
				query['ch_elem[filters]'] = $_('sel_search').value;
			}
			return query;
		}

		var autocomplete = new objAutocompleter({
			"objid" : "full_search_q", 
			"loader_show" : false,
			'checkTout' : 200,
			'minchars' : 3,
			'nowait' : true,
			'width' : 482,
			'left_offset' : 0,
			"ajxhref" : "/ajax.php?resource=ac&lang_id="+lang_id, 
			"callbacks" : {'before' : autocomp_callback, "apply" : ac_apply_callback}
			});

		$('#b-search-form').bind('submit', function(e){
			e.returnValue = false;
			e.preventDefault ? e.preventDefault() : '';
			ac_apply_callback(null, null);
			return e.returnValue;
		})
	}
	
	if ($('.b-search-field').length > 0){
	
		$('.b-search-field span').click(function(){
			$('#search-q').val('');
			$('#search-q')[0].focus();
			});	
	}
	
	
	// connect send to friend links
	if ($('.b-send-friend').length > 0){
		function f_click(el, index){
			$(el).click(function(e){addMailerClick(el, index)});
		}
		
		$('.b-send-friend').each(function (index, el){
			var i = index + 1;
			oFMailer[i] = new FMailer({'elem' : 'oFMailer'+i, 'add_id' : i, 'ajx_href' : document.location.pathname+'smphr/1/fmailer/yes/'});
			f_click(el, i);
		});			
	}
		
	// update current date 
	if ($('.g-current-time').length > 0){
		var dt = new Date();
	    var d = (dt.getDate()).toString();
	    if (d.length < 2) d = "0"+d;

		$('.g-current-time')[0].innerHTML = d +' '+ portal.mess.monthes[dt.getMonth()] +' '+ dt.getFullYear();
	}
		
	// connect print links
	if ($('.b-ico-print').length > 0){
		$('.b-ico-print').click(function (){portal.print()});
	}
	
	// forum
	$('.forum_slider, .forum_slider_active').bind('click', function() {
		var today = new Date();
		var expire = new Date();
		expire.setTime(today.getTime() + 3600000*24*365);
		
		if($('.right_part').css('display') == 'none') {
			setCookie('forum_noright', 0, expire.toGMTString());
			$('.right_part').show();
			$('.cntr').addClass('center_part');
			$('.forum_slider_active').removeClass('forum_slider_active').addClass('forum_slider');
		}else{
			setCookie('forum_noright', 1, expire.toGMTString());
			$('.right_part').hide();
			$('.cntr').removeClass('center_part');
			$('.forum_slider').removeClass('forum_slider').addClass('forum_slider_active');
		}
	});
    
	// checking for input hash
	if (document.location.hash){
		parseHash();	
	} 
};


/** document ready function **/
portal.ready(function(){

	portal.banners.setup();	
	
	if ($('.date-pick').length > 0){
		$('.date-pick').datePicker({startDate:'01/01/1900'});
	}

});
