jQuery(document).ready(function() {
        CActionController.init();
});


if (!Array.prototype.indexOf) { 
	Array.prototype.indexOf = function (item, i) {
		i || (i = 0);
		var length = this.length;
		if (i < 0) i = length + i;
		for (; i < length; i++)
			if (this[i] === item) return i;
		return -1;
	}
}



/**
  * Action controller
  * 
  */
(
	function( $ ){
		var strLocation = window.location.href;
		var strHash = window.location.hash;
		var strPrevLocation = "";
		var strPrevHash = "";
		var intIntervalTime = 100;
				
		var fnCleanHash = function( strHash ){ return(strHash.substring( 1, strHash.length ));};
		var fnCheckLocation = function(){
			if (strLocation != window.location.href){
				strPrevLocation = strLocation;
				strPrevHash = strHash;
				strLocation = window.location.href;
				strHash = window.location.hash;
				$( window.location ).trigger(
					"change",
					{
						currentHref: strLocation,
						currentHash: fnCleanHash( strHash ),
						previousHref: strPrevLocation,
						previousHash: fnCleanHash( strPrevHash )
					}
				);
			}
		}
		setInterval( fnCheckLocation, intIntervalTime );
	}
)( jQuery );

var CActionController = {
	
	  options				: {}
	, bind					: {
			'billing'		: 'CBillingPopup',
			'media'			: 'CMP',
			'spotlite'		: 'SPL',
			'ms'			: 'CMessengerCtrl',
			'subprofile'	: 'CSubProfile'
	}
	, regObject				: /#([^\/]*)(\/([^\/]*)(\/|$))?/i
	, init					: function() {

		if (this.regObject.test(window.location.href)) { this.ActionCallForce(); }
		
		jQuery( window.location ).bind(
			'change',
			function (event, data) {
				CActionController.ActionCallForce();
			}
		)		
	}
	, ActionCallForce		: function() {
		
		var r = window.location.hash ? window.location.hash.substr(1, window.location.hash.length - 1) : '';
		if (!r) { return; }		
		r = r.split('/');		
		if (!r[0]) { r.shift();	}		
		if (r.length < 2) { return; }
		
		if ( jQuery.isFunction( window[this.bind[r[0]]] && window[this.bind[r[0]]].__call )) {			
			a = [];
			if (r.length > 2) {				
				for (var i = 2; i < r.length; i++) {
					a.push(r[i]);
				}
			}
			window[this.bind[r[0]]].__call(r[1], a);
		}
//		var r = this.regObject.exec(window.location.href);
//		if ( jQuery.isFunction( window[this.bind[r[1]]] && window[this.bind[r[1]]].__call )) {
//			window[this.bind[r[1]]].__call(r[3]);
//		};
	}
};;

var IActionController = {
	__call				: function (action, args) {		
		if ( jQuery.isFunction(this['action_' + action.toLowerCase()])) {
			this['action_' + action.toLowerCase()].apply(this, args);			
		}
		else {
			if (console && console.log) {
				console.log(action);
			}
		}
	},
	
	__exit				: function() {
		window.location.hash = '';
	}
};;


/**
 * @author Samele Artuso <samuele.a@gmail.com>
 */
(function($) {
	$.fn.unselectable = function() {
		return this.each(function() {
			
			$(this)
				.css('-moz-user-select', 'none')		// FF
				.css('-khtml-user-select', 'none')		// Safari, Google Chrome
				.css('user-select', 'none');			// CSS 3
			
			if ($.browser.msie) {						// IE
				$(this).each(function() {
					this.ondrag = function() {
						return false;
					};
				});
				$(this).each(function() {
					this.onselectstart = function() {
						return (false);
					};
				});
			} else if($.browser.opera) {
				$(this).attr('unselectable', 'on');
			}
		});
	};
})(jQuery);

/**
 * Cookie plugin
 *
 * Copyright (c) 2006 Klaus Hartl (stilbuero.de)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 *
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};



var PhotoSlider	 = {
	
		Slider			: null
		
	,	interval_inc	: null
	,	interval_dec	: null
	
	,	options			: {}
	
	,	init			: function(o) {
			o = o || {};
			
			this.value			= parseInt( o.default_value ) ? parseInt( o.default_value) :140;
			this.max_value		= 140;
			this.min_value		= 100;
			this.LARGE_RELOAD_S	= 142;
			
			this.Slider = jQuery(o.element).slider({
				orientation: 'horizontal',
				range: "min",
				min: this.min_value,
				max: 450,
				value: this.value,
				slide: jsCore.delegate(this, 'refreshNodes'),
				change: jsCore.delegate(this, 'refreshNodes')
			});;
			
			this.Nodes = jQuery(o.nodes);
			
			this.Nodes.each(function () {				
				this.ratio		= this.width/this.height;
				this.photoId	= this.src.match(/\/(\d+)_/)[1]*1;
				this.Src		= {};
			});
			
			jQuery(o.element_inc).click(function () {return false; });
			jQuery(o.element_dec).click(function () {return false; });
			
			if (o.disabled) {
				this.Slider.slider('disable');
				this.Slider.click(function () { window.location.href = o.billing });
			}
			else {			
				jQuery(o.element_inc)
					.mousedown(jsCore.delegate(this, 'CL_inc_start'))
					.mouseup(jsCore.delegate(this, 'CL_inc_stop'));
					
				jQuery(o.element_dec)
					.mousedown(jsCore.delegate(this, 'CL_dec_start'))
					.mouseup(jsCore.delegate(this, 'CL_dec_stop'));
					
				if (this.value >= this.LARGE_RELOAD_S) { this.refreshNodes(); }
			}
				
	}
	
	,	refreshNodes	: function() {	
			
			var val		= this.Slider.slider('value');
			$.cookie('_pSlider_', val, { path: '/', expires: 60 });
			var reload	= 0;
			if ((val >= this.LARGE_RELOAD_S) && (this.max_value < this.LARGE_RELOAD_S)) { reload = 1; }
			this.Nodes.each(function () {
								
				this.style.width=(val*this.ratio)+'px';
				this.style.height=val+'px';
				if (reload) {
					
					document.images[this.name].src = $(this).attr('large');	
					
//					if (jQuery.browser.msie) { this.src = this.Src[1]; }
//					else { this.src = this.Src[1]; }
				}
			});
			if (this.max_value < val) this.max_value = val;
			$(".controls").css('width', function(){ return $(this).parent().width();} );
	}
	
	
	,	CL_inc_start	: function() { this.interval_inc = setInterval(jsCore.delegate(this, 'inc', 2), 20); }	
	,	CL_inc_stop		: function () { if (this.interval_inc) clearInterval(this.interval_inc); }
	,	CL_dec_start	: function() { this.interval_dec = setInterval(jsCore.delegate(this, 'inc', -2), 20); }
	,	CL_dec_stop		: function () { if (this.interval_dec) clearInterval(this.interval_dec); }
	
	,	inc				: function(val) {
			var cur = this.Slider.slider('value');
			this.Slider.slider('value', cur  + val);
	}
	
};

/**
  * Загрузка фотографий
  */
var CMP = jQuery.extend({}, IActionController, {
		options 			: {
				modalURL		: '/ajax/mediahosting/form_add_photo.php'
			,	popupID			: 'UploadForm'
			
		}
		
	,	init			: function (options) {		
			this.options = jQuery.extend({}, this.options, options || {});		
		}
		
	,	action_file		: function () { this.pre_show_modal(this.CL_action_file, this); }
	,	CL_action_file	: function () {  
			var a = 'file';
			var P = $('#' + this.options.popupID); 
			jQuery('#cmp-action-' + a, P).addClass('current');
			jQuery('#uploader-form-' + a, P).show();
			jQuery('#cmp-content-control-' + a, P).show();
		}
	
	,	action_cam		: function () { this.pre_show_modal(this.CL_action_cam, this); }	
	,	CL_action_cam	: function () {
			var a = 'cam';
			var P = $('#' + this.options.popupID);
			jQuery('#cmp-action-' + a, P).addClass('current');
			jQuery('#uploader-form-' + a, P).show();
			jQuery('#cmp-content-control-' + a, P).show();
		}
	
	,	action_url		: function () { this.pre_show_modal(this.CL_action_url, this); }
	,	CL_action_url	: function () { 
			var a = 'url';
			var P = $('#' + this.options.popupID);
			jQuery('#cmp-action-' + a, P).addClass('current');
			jQuery('#uploader-form-' + a, P).show();
			jQuery('#cmp-content-control-' + a, P).show();
		}
	
	,	action_close		: function () {
			jQuery('#' + this.options.popupID).hide();

			if(jQuery('.LB-popup:visible').size() == 0) {
				jQuery('#overlay').hide();	
			}
			this.__exit();
			window.location.reload();
		}
	
	
	,	pre_show_modal		: function(callback, obj) {
		
			var P = $('#' + this.options.popupID);
			if (P.size() == 0) {
				$.ajax({
					'async'			: false,
					'url'			: this.options.modalURL,
					'type'			: 'GET',
					'dataType'		: 'html',
					'success'		: function(r) {
						P = jQuery(r).attr('id', CMP.options.popupID).first().appendTo('body');
						
						if (P.is(':visible')) { P.hide(); }
											
						$(document).keypress(CMP.CL_popup_hide);
						P.find('.close').click(function () { CMP.go_to('close'); });
						
						CMP.CL_init_popup();
					}
				});
			}

			jQuery('.cmp-action', P).removeClass('current');
			jQuery('.cmp-content', P).hide();
			jQuery('.cmp-content-control', P).hide();
						
			this.popup_show();
			
			if (jQuery.isFunction (callback)) { callback.call(obj); }
		}
	,	CL_init_popup		: function () {
			
			var uid = jsCore.getUniqId();
			jQuery('#' + this.options.popupID).append('<iframe style="position: absolute; visibility: hidden; width: 1px; height: 1px;" name="' + uid + '" src="about:blank"></iframe>');
			jQuery('iframe[name=' + uid + ']').load(function () {
				var iFrameBody;
				if (this.contentDocument ) { // FF
					iFrameBody = this.contentDocument.getElementsByTagName('body')[0];
				} else if ( this.contentWindow ) { // IE
					iFrameBody = this.contentWindow.document.getElementsByTagName('body')[0];
				}
				var response;
				if (!iFrameBody || !iFrameBody.innerHTML.length) {
					return;
				}
				
				eval('response = ' + iFrameBody.innerHTML);
				CMP.CL_SubmitFile(response);
			});
			
			jQuery('#uploader-form-file').attr('target', uid);;
			jQuery('#uploader-form-cam').attr('target', uid);;
			
			jQuery('#cmp-content-submit-file').click(function () { jQuery('#uploader-form-file').submit(); return false; });
			jQuery('#cmp-content-submit-url').click(function () { jQuery('#uploader-form-url').submit(); return false; });
			
			jQuery('form', jQuery('#' + this.options.popupID)).each(function () {
				var F = $(this);
				F.append('<input type="hidden" name="user_id" value="' + CMP.options.byUserID + '" />');
			});
			
			var c = 'Test123';
			window[c] = function(n, r) { CMP.CL_SubmitFile(r); };
			SWF.build(
				this.options.idRecorderSwf,
				{
					movie:{ url:this.options.recorderUrl, width:this.options.recorderWidth, height:this.options.recorderHeight },
					vars:{ jsCallback: c, quality:this.options.recorderQuality, uri:this.options.recorderURI, min_record_duration:this.options.recorderMinDuration, max_record_duration:this.options.recorderMaxDuration, use_amf3:this.options.recorderUseAmf3 },
					params:{wmode:'opaque'}
				}
			)
			
			// from web
			jQuery('#uploader-form-url').unbind('submit').submit(function (e) {
				e.preventDefault();
				var F = jQuery(this);
				F.find('.error').remove();
				jQuery.post(
					F.attr('action'),
					F.serialize(),
					CMP.CL_SubmitFile,
					'json'
				)
				
			});
			
			jQuery('#cmp-add-more').click(function (e) { e.preventDefault; CMP.CL_add_more(); });			
		}

	,	CL_popup_hide		: function (event) {
			if (event.keyCode == 27 && jQuery('#' + CMP.options.popupID).is(':visible')) { CMP.go_to('close'); }		
		}
		
	,	CL_SubmitFile : function(response) {
			if (typeof response != "object") { eval( "response = " + response ); }
			
			var cur = $('.cmp-content:visible');
			var cur2 = $('.cmp-content-control:visible');
			this.last_action = cur;
			this.last_action2 = cur2;
			
			var res = $('#cmp-content-result');			
			var res2 = $('#cmp-content-control-result');			
			$('.cmp-message').hide();
			
			if (response && response.status && response.status == "OK") {
				cur.hide();
				cur2.hide();
				res.show();
				res2.show();
				$('#cmp-result-ok').show();
			}
			else if (response && response.status && response.status == "ER") {
				cur.hide();
				cur2.hide();
				res.show();
				res2.show();
				var e = '';
				for(var i in response.errors) {
					if (!e) {
						e = response.errors[i];
					}
				}
				
				var err = $('#cmp-result-err').html(e).show();
			}
		}
	,	CL_add_more	: function () {
			if (this.last_action) {
				this.last_action.show();
				this.last_action2.show();
			}
			$('#cmp-content-result').hide();
		}
			
		
	,	popup_show	: function () {
			if (jQuery('div#overlay').size() == 0) {		
				jQuery('body').append('<div id="overlay" class="overlay"></div>');
			}
			jQuery('#overlay').height( jQuery('.ap-wrapper').height() ).show();	
			jQuery('#' + this.options.popupID).show();
		}		
		
	,	go_to		: function(step) { window.location.href = "#media/" + step; }
});;


/**
  * Добавление профайла
  */
var CSubProfile = jQuery.extend({}, IActionController, {	
		options 			: {			
				defaultService	: 'vip'
			,	currentService	: 'vip'
			,	modalURL		: '/ajax/sub_profile_modal.php'
			,	popupID			: 'SubProfilePopup'
			
		}
	,	action_add			: function () {
			$('#' + this.options.popupID).remove();
			this.pre_show_modal();
		}
		
	,	action_edit			: function (user_id) {
			$('#' + this.options.popupID).remove();
			this.pre_show_modal(user_id);
			
		}

	,	action_close		: function () {
			jQuery('#' + this.options.popupID).hide();

			if(jQuery('.LB-popup:visible').size() == 0) {
				jQuery('#overlay').hide();	
			}
			this.__exit();
		}
		
	,	action_remove		: function(uid) {
			$.post(
				'/ajax/user_delete.php',
				{'child' : uid},
				function (resp) {
					if (resp && resp.redirect) {
						window.location.href = resp.redirect;
					}
					else {
						CSubProfile.go_to('close');
					}
				},
				'json'				
			);
		}

	
	,	pre_show_modal		: function(user_id) {
		
			if (!user_id) { user_id = ''; }
		
			var P = $('#' + this.options.popupID);
			if (P.size() == 0) {
				$.ajax({
					'async'			: false,
					'url'			: this.options.modalURL,
					'data'			: { child_id : user_id },
					'type'			: 'GET',
					'dataType'		: 'html',
					'success'		: function(r) {
						P = jQuery(r).attr('id', CSubProfile.options.popupID).first().appendTo('body');
						
						if (P.is(':visible')) { P.hide(); }
											
						$(document).keypress(CSubProfile.CL_popup_hide);
						P.find('.close').click(function () { CSubProfile.go_to('close'); });
						
						CSubProfile.CL_init_popup();
					}
				});
			}
						
			this.popup_show();
		}

	,	popup_show	: function () {
			if (jQuery('div#overlay').size() == 0) {		
				jQuery('body').append('<div id="overlay" class="overlay"></div>');
			}
			jQuery('#overlay').height( jQuery('.ap-wrapper').height() ).show();	
			jQuery('#' + this.options.popupID).show();
		}		
		
	,	CL_init_popup		: function () {
		
			var P = $('#' + this.options.popupID);
			var F = $('form', P);
			
			F.submit(function (e) {
				e.preventDefault();
				var F = jQuery(this);
				F.find('.invalid').removeClass('invalid');
				F.find('.ap-form-msg').hide();
				jQuery.post(
					F.attr('action'),
					F.serialize(),
					CSubProfile.CL_SubmitForm,
					'json'
				)
			});		
		}
	,	CL_SubmitForm		: function (resp) {
		
			if (resp && resp.status == "OK") {
				if (resp.redirect) {
					window.location.href = resp.redirect;
				}
			}
			else if (resp && resp.status == 'ER') {
				
				var e = resp.errors;
				if (e.NAME) {
					$('#SUBF-c-name').addClass('invalid').find('.ap-form-msg').show();
				}
				
				if (e.GENDER) {
					$('#SUBF-c-gender').addClass('invalid').find('.ap-form-msg').show();
				}
				
				if (e.BIRTHDAY) {
					$('#SUBF-c-birthday').addClass('invalid').find('.ap-form-msg').show();
				}

				return;			
			}
			else {
				this.go_to('close');
			}		
		}
		
	,	CL_popup_hide		: function (event) {
			if (event.keyCode == 27 && jQuery('#' + CSubProfile.options.popupID).is(':visible')) { CSubProfile.go_to('close'); }		
		}
		
		
	,	go_to		: function(step) { window.location.href = "#subprofile/" + step; }
});;


/**
  * Общение
  */
var CMessengerCtrl = jQuery.extend({}, IActionController, {
	
		options 			: {
				popupID			: 'MS-Popup'
			,	modalURL		: '/ajax/messenger/main_frame.php'
			,	userInfoURL		: '/ajax/messenger/user_info.php'
			
			,	tabTemplate		: '<div><a href="#href#" class="MS-tab" id="MS-tab-#uid#"><img src="#src#" alt="" width="75" /></a></div>'
			,	no_photo_src	: ''
		}
	,	apiTabs				: null
	,	refresh_checknew	: null
	
	,	tabs				: {}
	,	unread				: {}
	
	,	personalDataDefault	: {
			image		: '',
			name		: '',
			age			: '',
			gender		: '',
			location	: '',
			profile		: '',
			is_vip		: false,
			is_online	: false		
		}

	,	action_read			: function (uid, offset) { 
			this.pre_show_modal(); 
			if (this.add_tab(uid)) {
				this.activate_tab(uid, offset);
				this.popup_show();	
			}			
		}
		
	,	action_close		: function () {
			jQuery('#' + this.options.popupID).hide();
			if(jQuery('.LB-popup:visible').size() == 0) { jQuery('#overlay').hide(); }
			
			this.EL_CheckNewMessagesStop();
			this.__exit();
		}
		
	,	add_tab				: function(uid) {
			
			if (jQuery('#MS-tab-' + uid).size() > 0) { return true; }
			var tab = this.get_tab(uid);
			if (!tab) return false;
			
			var el = jQuery(this.options.tabTemplate.replace('#uid#', uid).replace('#src#', tab.image ? tab.image : this.options.no_photo_src).replace('#href#', '#ms/read/' + uid));
			this.apiTabs.addItem(el);
			
			jQuery('#MS-tab-' + uid).bind('messenger-contact-new-msg',function (event) {
				if ( jQuery('#MS-tab-' + uid).is('.active') ) {
					CMessengerCtrl.refreshMessageBox(); 
				}
			});
			
			return true;
		}
		
	,	activate_tab		: function (uid, offset) {
			jQuery('.MS-tab.active').removeClass('active');
			jQuery('#MS-tab-' + uid).addClass('active');
			
			var tab = this.get_tab(uid);
			jQuery('#MS-profile-name').attr('href', tab.profile).html(tab.name);
			jQuery('#MS-profile-age').html(tab.age);
			jQuery('#MS-profile-location').html(tab.location);

			jQuery('#MS-box').attr('disabled', !tab.is_active).val('');
			
					
			this.refreshMessageBox(offset);
			
		}
			
	,	get_tab				: function(uid) {
		
			if (this.tabs[uid]) {				
				return jQuery.extend({}, this.tabs[uid]);
			}
			
			$.ajax({
				'async'			: false,
				'url'			: this.options.userInfoURL,
				'data'			: { u : uid },
				'type'			: 'POST',
				'dataType'		: 'json',
				'success'		: function(r) {	

					if (r && r.data) {
						for ( var u in r.data) {
							CMessengerCtrl.addPersonalData(u, r.data[u]);
						}
					}
					
				}
			});
			return jQuery.extend({}, this.tabs[uid]);
		}
		
	,	addPersonalData		: function(uid, data) {			
			this.tabs[uid] = jQuery.extend(jQuery.extend({},this.personalDataDefault), data);		
		}
		
	,	refreshMessageBox			: function(offset) {
			
			var user_id = /\d+/.exec(jQuery('.MS-tab.active').attr('id'));
			if (!user_id) { return; }
			user_id = user_id[0];
			var DT = new Date();			
			$.get(
				$('#MS-form-message-list').attr('action'),
				{ 
					'userId' : user_id,
					'uniq'	 : DT.getTime(),
					'offset' : offset
				},
				function(response) { 
					jQuery('#MS-message-list').html(response);
					
					jQuery('.MS-pager a').each(function () { 
						var T = $(this);
						T.attr('href', '#ms/read/' + user_id + '/' +  T.attr('href')); 
						jQuery('#MS-refresh-message-list').click(function () { CMessengerCtrl.refreshMessageBox(); return false; });
					});
				},
				'html'				
			);
		}
		
	,	EL_CheckNewMessagesStart	: function() {
		
			$form = $('#MS-form-checknew');
		
			if (this.refresh_checknew) {
				clearInterval(this.refresh_checknew);
				this.refresh_checknew = null;
			}
						
			this.refresh_checknew = setInterval(function () {
				
					var link = $form.attr('action');
					var DT   = new Date();
				
					$.get(
						link,
						{
							'action'		: 'unread',													
							'reqid'			: DT.getTime()
						},
						function (response) {
							if (response && response.status == "OK") {
								CMessengerCtrl.unreadClear();
								for (i = 0; i < response.data.length; ++i) {
									CMessengerCtrl.unreadNotify(response.data[i].id, response.data[i].count);
								}
							}							
						},
						'json'
					);
				
				}, 3000);
		}
		
	,	EL_CheckNewMessagesStop		: function () {
			
			if (this.refresh_checknew) {
				clearInterval(this.refresh_checknew);
				this.refresh_checknew = null;
			}
			
		}	
		
	, 	postMessage					: function () {
		
			var user_id = /\d+/.exec(jQuery('.MS-tab.active').attr('id'));
			if (!user_id) { return; }
			user_id = user_id[0];
						
			var message = $('#MS-box').val();
			var form = $('#MS-box').parents('form');
			
			if (!message) { return; }
			
			$.post(
				form.attr('action'),
				{
					'userId' : user_id,
					'message' : message
				},
				function (response) {
					if (response.status == "OK") { 
						CMessengerCtrl.refreshMessageBox(); 
						$('#MS-box').val('');
					}
					else if (response.status = 'ER') {
						window.location.hash = 'billing/start';
					}
				},
				'json'			
			);
		}
		
	,	unreadClear			: function() { this.unread = {}; }
	,	unreadNotify		: function(uid, msg_count) {
			this.unread[uid] = msg_count;
			jQuery('#MS-tab-' + uid).trigger('messenger-contact-new-msg');
		}
	
	,	pre_show_modal		: function(callback, obj) {
		
			var P = $('#' + this.options.popupID);
			if (P.size() == 0) {
				$.ajax({
					'async'			: false,
					'url'			: this.options.modalURL,
					'type'			: 'GET',
					'dataType'		: 'html',
					'success'		: function(r) {
						
						P = jQuery(r).attr('id', CMessengerCtrl.options.popupID).first().appendTo('body');
						if (P.is(':visible')) { P.hide(); }
						$(document).keypress(CMessengerCtrl.CL_popup_hide);
						P.find('.close').click(function () { CMessengerCtrl.go_to('close'); });
						
						CMessengerCtrl.CL_init_popup();
					}
				});
			}					
		}
		
	,	CL_init_popup		: function () {
			//карусель и тп....
			$('#MS-tabs').scrollable({});
			this.apiTabs = $('#MS-tabs').data("scrollable");
			
			jQuery('#MS-box').parents('form')
				.unbind('submit').submit(function (event) {
					event.preventDefault();
					CMessengerCtrl.postMessage();
				});
			// key bindings
			$('#MS-box').keydown(function (event) {
				if (event.ctrlKey && event.keyCode == 13) { CMessengerCtrl.postMessage(); }
			});
		}
		
	,	popup_show			: function () {
			if (jQuery('#overlay').size() == 0) {
				jQuery('body').append('<div id="overlay" class="overlay"></div>');
			}
			jQuery('#overlay').height( jQuery('.ap-wrapper').height() ).show();
			jQuery('#' + this.options.popupID).show();
			
			this.EL_CheckNewMessagesStart();
		}
		
	,	CL_popup_hide		: function (event) {
			if (event.keyCode == 27 && jQuery('#' + CMessengerCtrl.options.popupID).is(':visible')) { CMessengerCtrl.go_to('close'); }		
		}
				
	,	go_to		: function(step) { window.location.href = "#ms/" + step; }
});;

/**
  * оплата вип услуги 
  */
var CBillingPopup = jQuery.extend({}, IActionController, {
	
		options 			: {
			
				defaultService	: 'vip'
			,	currentService	: 'vip'
			,	modalURL		: '/ajax/billing/modal.php'
			,	popupID			: 'BillingPopup'
			
		}
		
	,	popup				: null
	,	periodic_check		: null
	
	,	__consturct			: function () {	
		
	}
	
	,	action_start		: function () { this.pre_show_modal(this.CL_action_start, this); }	
	,	CL_action_start		: function () {
		
			var box = this.popup.find('#billing-method-sms');
			if (!box.size()) { 
				this.go_to('settings');
				return false;
			}
			else {
				box.show();
				this.show_modal();
			}
	}
	,	action_settings		: function () { this.pre_show_modal(this.CL_action_settings, this); }
	,	CL_action_settings	: function () {
			
			var box = this.popup.find('#billing-method-emoney');
			
			if (!box.size()) { 
				this.go_to('cancel'); 
				return false; 
			}
			else {
				box.show();
				var SF = this.popup.find('#SettingsForm');
				SF.show();
				this.show_modal();
			}
	}	
	,	action_pay			: function () { this.pre_show_modal(this.CL_action_pay, this); }
	,	CL_action_pay		: function () {
			
			var box = this.popup.find('#billing-method-emoney');
			
			if (!box.size()) { 
				this.go_to('cancel'); 
				return false; 
			}
			else {
				box.show();
				box.find('.steps').children('div').attr('class', '').addClass('second').find('td').removeClass('active').end().find('td:nth-child(2)').addClass('active');
				
				var RF = this.popup.find('#RoboxForm');
				var SF = this.popup.find('#SettingsForm');
				
				var Price = SF.find('input[name=price]:checked').val();
				var Method = SF.find('input[name=billing_type]:checked').val();
				
				RF.find('input[name=billing_type]').val(Method);
				RF.find('input[name=price]').val(Price);
				
				RF.find('#billing-final-price').html(Price);
				RF.find('#billing-final-period').html( SF.find('#billing-period-' + Price).html() );
				var discount = SF.find('#billing-period-' + Price).parent().find('.billing-discount').html();
				
				if (discount) {
					RF.find('#billing-final-disount-block').show().find('#billing-final-discount-value').html(discount);
				}
				else {
					RF.find('#billing-final-disount-block').hide();
				}
				
				RF.find('.more-fields').hide();
				RF.find('#BT-' + Method).show();
				
				RF.show();
				this.show_modal();
			}
	}
	,	start_transaction	: function () {		
			CAjaxLoaderIndicator.target(this.popup.find('#RoboxForm .ap-paging td.result'));
			var RF = this.popup.find('#RoboxForm');

			jQuery.post(
				RF.attr('action'),
				RF.serialize(),
				function (response) { CBillingPopup.CL_start_transaction.call(CBillingPopup, response) },
				'json'
			);
	}
	,	CL_start_transaction: function (response) {
		
			if (response && response.status == 'OK') {
				var trID = response.data.trID;
				var RF = this.popup.find('#RoboxForm');
				var P = function () {
					jQuery.post(
						RF.attr('action'),
						{'trID' : trID, 'act': 'check' },
						function (response) { CBillingPopup.CL_check_transaction.call(CBillingPopup, response) },
						'json'
					);
				}
				this.periodic_check = setInterval( P, 2000 );
				P();
			}
			else if (response && response.status == 'ER') {
				if (this.periodic_check) { clearInterval(this.periodic_check); }
				CAjaxLoaderIndicator.clear(this.popup.find('#RoboxForm .ap-paging td.result'));
			}
	}	
	,	CL_check_transaction: function (response) {
		
			if (response && response.status == 'OK') {				
				if (response.data.result && response.data.redirect) {					
					if (this.periodic_check) { clearInterval(this.periodic_check); }
					CAjaxLoaderIndicator.clear(this.popup.find('#RoboxForm .ap-paging td.result'));
					window.location.href = response.data.redirect;
				}
			}
			else if (response && response.status == 'ER') {
				if (this.periodic_check) { clearInterval(this.periodic_check); }
				CAjaxLoaderIndicator.clear(this.popup.find('#RoboxForm .ap-paging td.result'));
			}
	}	
	
	,	action_success		: function () { { this.pre_show_modal(this.CL_action_success, this); } }
	,	CL_action_success	: function () {
			var box = this.popup.find('#billing-method-emoney');
			if (!box.size()) { 
				this.go_to('cancel');
				return false;
			}
			else {
				box.show();
	
				var RF = this.popup.find('#ReportForm');
				RF.find('#billing-success').show();
				RF.find('#billing-error').hide();				
				RF.show();
				
				this.show_modal();
			}		
	}
	,	action_fail			: function () { this.pre_show_modal(this.CL_action_fail, this); }
	,	CL_action_fail		: function () {
			var box = this.popup.find('#billing-method-emoney');
			if (!box.size()) { 
				this.go_to('cancel');
				return false;
			}
			else {
				box.show();
			
				var RF = this.popup.find('#ReportForm');
				RF.find('#billing-error').show();
				RF.find('#billing-success').hide();				
				RF.show();				
				this.show_modal();
			}		
	}
	,	action_cancel		: function () { this.action_close(); }
	,	action_close		: function () {			
			this.popup && this.popup.hide();
			if(jQuery('.LB-popup:visible').size() == 0) {
				jQuery('#overlay').hide();	
			}
			this.__exit();
	}
	
	
	
	
	,	show_modal			: function () {
		
			if (jQuery('div#overlay').size() == 0) {		
				jQuery('body').append('<div id="overlay" class="overlay"></div>');
			}
			jQuery('#overlay').height( jQuery('.ap-wrapper').height() ).show();
			jQuery('#' + this.options.popupID).show();
	}
	
	,	pre_show_modal		: function(callback, obj) {
			if (!this.popup) {
				jQuery('body').append('<div class="ap-l LB-popup" id="' + this.options.popupID + '"></div>');
				this.popup = jQuery('#' + this.options.popupID);				
			}
			if (this.popup.find('#billing-service-' + this.options.currentService).size() == 0) {
				jQuery.post(
					this.options.modalURL,
					{'service' : this.options.currentService, 'url' : window.location.pathname },
					function (resp) {						
							CBillingPopup.popup.append(resp);
							CBillingPopup.popup.find('.billing-inside').hide();
							CBillingPopup.popup.find('form').hide();	
							CBillingPopup.ui_settings();
							if (jQuery.isFunction (callback)) { callback.call(obj); }
					},
					'html'
				);
			}
			else {
				this.popup.find('.billing-inside').hide();
				this.popup.find('form').hide();				
				if (jQuery.isFunction (callback)) { callback.call(obj); }
			}
	}
	
	,	ui_settings			: function () {	
			
			this.popup.find('.close').click(function (e) { window.location.hash='#billing/cancel'; return false; });
			
			// start
			this.popup.find('.bottom.pays a.emoney-methods').click(function (e) {
				e.preventDefault();
				CBillingPopup.popup.find('#SettingsForm input[name=billing_type][value=' + $(this).attr('value') + ']').attr('checked' , 'checked');
				CBillingPopup.go_to('settings');
			});
			this.popup.find('#billing-method-sms .discounts a').click(function (e) {
				e.preventDefault();
				CBillingPopup.popup.find('#SettingsForm input[name=price][value=' + $(this).attr('value') + ']').attr('checked' , 'checked');
				CBillingPopup.go_to('settings');
			});
			
			// settings			
			this.popup.find('#SettingsForm').unbind('submit').submit(function (e) { e.preventDefault(); CBillingPopup.go_to('pay'); });			
			if (this.popup.find('#billing-method-sms').size() == 0) { this.popup.find('#SettingsForm .ap-back').click(function() { return false; }).parent().addClass('ap-disabled'); }
			
			//pay
			this.popup.find('#RoboxForm').unbind('submit').submit(function (e) { e.preventDefault(); CBillingPopup.start_transaction(); });
			
			jQuery(document).keydown(function (e) { if (e.keyCode == 27 && $('#' + CBillingPopup.options.popupID + ':visible').size() > 0) { CBillingPopup.go_to('cancel'); } });
	}
	
	,	go_to				: function(step) { window.location.href = "#billing/" + step; }
});;


var CAjaxLoaderIndicator = {
		
		options				: {
			  length		: 9
			, dot			: '|'
			, dot_ms		: 400
			, css_container	: 'CALoader'
			, css_element	: 'CALoader-element'
			
		}
		
	,	current				: {}
	,	current_next		: 0
	
	,	target				: function (element, options) {
		
			var O = jQuery.extend({}, this.options, options || {});
			var E = jQuery(element);
			
			if (!E.size() || E.size() > 1) { return false; }
			
			var id = "CALoader" + this.current_next++;
			var L = jQuery(this.parse(O));
			L.attr('id' , id);
			L.find('.' + O.css_element).hide();		
			E.append(L);
			
			var save = {'e' : E.get(0), 'l' : L, 'o': O}
			var func = function () {
				var dot = save.l.find('.' + save.o.css_element + ':hidden:first');
				if (dot.size() == 0) {
					save.l.find('.' + save.o.css_element).hide();
				}
				else {
					dot.show();
				}
			};
			
			var periodID = setInterval( func, O.dot_ms )
			save.p = periodID;
			
			this.current[id] = save;			
	}
	
	,	clear				: function (element) {
			
			var E = jQuery(element);			
			if (!E.size() || E.size() > 1) { return false; }
			
			for (var id in this.current) {				
				if(this.current[id].e === E.get(0)) {
					clearInterval(this.current[id].p);
					this.current[id].l.remove();
					delete this.current[id];
				}
			}
	}
	
	,	parse				: function (options) {
			
			var html = "<span class='" + options.css_container + "'>";
			for (var i = 0; i < options.length; ++i) {
				html += "<span class='" + options.css_element + "'>" + options.dot + "</span>";
			}
			html += "</span>";
			
			return html;	
	}
	
};;

/**
  *
  * Выбиралка городов
  *
  */
(function($) {
	$.fn.locationSelector = function(options, lang) {
		
		$.fn.locationSelector.defaults = {
				'enable_enter'		: true
			,	'enable_choose'		: true
			,	'autoURL'			: '/ajax/geo.php'
			,	'popupURL'			: '/ajax/location.php?q=popup'
			,	'locationsURL'		: '/ajax/location.php'
			
			,	'deep_allow'		: 1 /* 0 - metro , 1 - city, 2 - region, 3 - country, 4 - any */
			,	'deep_restrict'		: 0 /* 0 - metro , 1 - city, 2 - region, 3 - country, 4 - any */
			
			,	'popupID'			: 'LS-popup'
			,	'css_choose'		: 'LS-choose'
			,	'css_enter'			: 'LS-enter'
			,	'css_enter_input'	: 'LS-enter-input'
			,	'value_choose'		: 'choose'
			,	'value_enter'		: 'enter'
			,	'popup_template'	: '<li><a href="#" value="#value#" class="LS-node">#name#</a></li>'
			
			,	'input_target'		: null
			,	'popupHandler'		: null
		};
		$.fn.locationSelector.language_default = {
				'choose'		: 'Выбрать из списка...'
			,	'enter'			: 'Ввести название...'
			,	'any_metro'		: 'Любая станция метро'
			,	'any_city'		: 'Все города'
			,	'any_region'	: 'Все регионы'
			,	'any_country'	: 'Все страны'
		};
		
		
		var opts	= $.extend({}, $.fn.locationSelector.defaults, options);
		var langs	= $.extend({}, $.fn.locationSelector.language_default, lang);
		
		return this.each(function() {
			var T = $(this);
			T.attr('init_value',T.val());
			if (this.tagName == 'SELECT') {
				addOptions(this);
				bindEventsSelect(this);
			}
			else if (T.is('input[type=text]')) {
				bindAutocomplete(T);
			}
			
			if (opts.popupHandler) {
				var H = $(opts.popupHandler);
				H.click(function () { CL_choose(T.get(0)); });
			}
			
		});
		
		function addOptions(select) {
			if (select.tagName != 'SELECT') { return false; }
			
			if (opts.enable_choose) {
				var o_choose = $("<option value='" + opts.value_choose + "' class='" + opts.css_choose + "'>" + langs.choose + "</option>");
				$(select).append(o_choose)
			}
			if (opts.enable_enter) {
				var o_enter = $("<option value='" + opts.value_enter + "' class='" + opts.css_enter + "'>" + langs.enter + "</option>");
				$(select).append(o_enter);
			}
		}
		
		function bindEventsSelect(select) {
			
			var S = $(select);
			S.change(function () {
				var val = $(this).val();
				if (val == opts.value_choose) { CL_choose(select); }
				else if (val == opts.value_enter) { CL_enter(select); }
			});
			
		}
		
		function bindAutocomplete(input, select) {
			var I = $(input);
			I.autocomplete(
				opts.autoURL,
				{
					delay:10,
					minChars:3,
					
					matchSubset:1,
					matchContains:1,
					
					cacheLength:1,
					autoFill:true,
					mustMatch:true,
					selectFirst:true,
					extraParams: {
						action: 'list',
						scountry: opts.deep_allow > 2 ? 1 : 0,
						sregion: opts.deep_allow > 1 ? 1 : 0
					}
				})
				.result(function (event, data, formated) {
					if (!data) { return; }
					if (select) {
						var S = $(select);
						if ($('option[value=' + data[1] + ']', S).size() == 0) {
							var Insert_before = $('option.' + ( opts.enable_choose ? opts.css_choose : opts.css_enter), S);
							Insert_before.before($('<option></option>').val(data[1]).text(data[0]));
						}
						CL_enter_cancel(select, data[1]);
					}
					else if (opts.input_target) {
						var T = $(opts.input_target);
						T.val(data[1]);
					}
				});
			
		}
				
		function CL_enter(select) {
			var S = $(select);
			var I = $('<input type="text" class="' + opts.css_enter_input + '" value="" />');
			I.keypress(function (e) { if (e.keyCode == 27) { CL_enter_cancel(select); } });
			S.after(I);			
			S.hide();
			bindAutocomplete(I, select);
			I.focus();
		}
		
		function CL_enter_cancel(select, option_value) {
			var S = $(select);
			var I = S.next('input.' + opts.css_enter_input);
			I.unbind('keypress');
			I.remove();
			S.show();
			if (option_value) {
				$('option[value=' + option_value + ']', S).attr('selected', 'selected');
			}
			else {
				$('option:first', S).attr('selected', 'selected');	
			}
		}
		
		function CL_choose(element) {
			popup_show(element);
			var init_value = $(element).attr('init_value') || '0_0_0_0';
			var e = init_value.split('_');
			if (e[3] > 0) {
				popup_fill(e[0], e[1], e[2], 0);
			}
			else {
				popup_fill(e[0], e[1], 0, 0);
			}
		}
		
		function CL_choose_cancel(option_value) {
			var element = $('#' + opts.popupID).get(0).linked;
			
			$('#' + opts.popupID).hide();
			if(jQuery('.LB-popup:visible').size() == 0) { jQuery('#overlay').hide(); }
			
			if (element && element.tagName == 'SELECT') {
				if (option_value) {
					$('option[value=' + option_value + ']', $(element)).attr('selected', 'selected');
				}
				else {
					$('option:first', $(element)).attr('selected', 'selected');	
				}
			}
			else { 
				if (opts.input_target) {
					var T = $(opts.input_target);
					T.val(option_value);
				}
			}			
			$('#' + opts.popupID).get(0).linked = null;
		}
		
		function popup_fill(country_id, region_id, city_id, metro_id) {
			country_id = parseInt(country_id);
			region_id = parseInt(region_id);
			city_id = parseInt(city_id);
			metro_id = parseInt(metro_id);
			var mod, rcity, rregion, rcountry;
			var req = {};
			if (city_id) {
				req['select'] = 'metro';
				req['countryId'] = country_id;
				req['regionId'] = region_id;
				req['cityId'] = city_id;
			}
			else if (region_id) { 
				req['select'] = 'city';
				req['countryId'] = country_id;
				req['regionId'] = region_id;
				req['cityId'] = 0;
			}
			else if (country_id) {
				req['select'] = 'region';
				req['countryId'] = country_id;
				req['regionId'] = 0;
				req['cityId'] = 0;
			}
			else {
				req['select'] = 'country';
				req['countryId'] = 0;
				req['regionId'] = 0;
				req['cityId'] = 0;
			}
			$.get(
				opts.locationsURL,
				req,
				function (response) { CL_popup_fill(response,req); },
				'json'
			);
		}
		
		function CL_popup_fill(response, request) {
			if (response.status && response.status != 'OK') { CL_choose_cancel(); return false; }
			
			var P	=  $('#' + opts.popupID);
			var L	=  P.find('.city-chooser');
			var s	=  "";
			L.find('.LS-node').unbind('click').unbind('dblclick');

			if (response.data.list.length == 0)
			{
				make_selection();
				return;
			}	
			L.html(s);
			
			if (request.select == 'metro') {
				P.find('#LS-change-link').show();
				P.find('.LS-change-link').hide();
				P.find('#LS-change-city').show();
				if (opts.deep_allow > 0) {
					s = s + opts.popup_template.replace('#name#', langs.any_metro).replace('#value#', '0');
				}				
			} 
			else if (request.select == 'city') {
				P.find('#LS-change-link').show();
				P.find('.LS-change-link').hide();
				P.find('#LS-change-region').show();
				if (opts.deep_allow > 1) {
					s = s + opts.popup_template.replace('#name#', langs.any_city).replace('#value#', '0');
				}
			}
			else if (request.select == 'region') {
				P.find('#LS-change-link').show();
				P.find('.LS-change-link').hide();
				P.find('#LS-change-country').show();
				if (opts.deep_allow > 2) {
					s = s + opts.popup_template.replace('#name#', langs.any_region).replace('#value#', '0');
				}
			} else if (request.select == 'country') {
				P.find('#LS-change-link').hide();
				if (opts.deep_allow > 3) {
					s = s + opts.popup_template.replace('#name#', langs.any_country).replace('#value#', '0');
				}				
			}
			
			for(var i = 0; i < response.data.list.length; ++i) {
				s = s + opts.popup_template.replace('#name#', response.data.list[i].name).replace('#value#', response.data.list[i].oid);
			}
			L.append(s);
			P.find('.LS-head').html(response.data.current);
			P.find('.LS-country').html(response.data.country);
			L.find('.LS-node').click(select_node).dblclick(proceed_selection);
			P.get(0).last_request = request;
		}
		
		function select_node(event/*click*/) {
			var L	=  $('#' + opts.popupID + ' .city-chooser');
			L.find('.LS-node').removeClass('selected');
			$(this).addClass('selected');
			return false;
		}
		
		function proceed_selection(event/*dblclick*/) {
			var E = $(this);
			var P = $('#' + opts.popupID);
			if (!E.is('.LS-node')) {
				E = $('.LS-node.selected', P);
				if (E.size() == 0) { return false; }
			}
			var lr = P.get(0).last_request;
			var deeper	= [];
			var deep = 100;
			switch (lr.select) {
				case 'metro':
					deep = 0;
					deeper.push(lr.countryId); deeper.push(lr.regionId);  deeper.push(lr.cityId); deeper.push(E.attr('value'));
					break;
				
				case 'city':
					deep	= 1;
					deeper.push(lr.countryId); deeper.push(lr.regionId); deeper.push(E.attr('value')); deeper.push(0);
					break;
									
				case 'region':
					deep	= 2;
					deeper.push(lr.countryId); deeper.push(E.attr('value')); deeper.push(0); deeper.push(0);
					break;
					
				case 'country':
					deep	= 3;
					deeper.push(E.attr('value')); deeper.push(0); deeper.push(0); deeper.push(0);
					break;
			}
			
			if (deep == opts.deep_restrict) { make_selection(); }
			else if (deeper.length >= 3) {
				popup_fill(deeper[0], deeper[1], deeper[2], 0);
			}
			
		}
		
		function make_selection(event/*click*/) {
			var P = $('#' + opts.popupID);
			var E = $('.LS-node.selected', P);
			if (E.size() == 0) { return false; }
			
			var deep	= 100; 
			var value	= '0_0_0_0';
			var deeper	= [];
			var lr = P.get(0).last_request;
			switch (lr.select) {
				case 'metro':
					deep = 0;
					value	= lr.countryId + '_' + lr.regionId + '_' + lr.cityId + '_' + E.attr('value');
					deeper.push(lr.countryId); deeper.push(lr.regionId); deeper.push(lr.cityId); deeper.push(E.attr('value'));
					break;
				
				case 'city':
					deep	= 1;
					value	= lr.countryId + '_' + lr.regionId + '_' + E.attr('value') + '_0';
					deeper.push(lr.countryId); deeper.push(lr.regionId); deeper.push(E.attr('value')); deeper.push(0);
					break;
				
				case 'region':
					deep	= 2;
					value	= lr.countryId + '_' + E.attr('value') + '_0_0';
					deeper.push(lr.countryId); deeper.push(E.attr('value')); deeper.push(0); deeper.push(0);
					break;
					
				case 'country':
					deep	= 3;
					value	= E.attr('value') + '_0_0_0';
					deeper.push(E.attr('value')); deeper.push(0); deeper.push(0); deeper.push(0);
					break;
			}
			if (deep <= opts.deep_allow) {
				var element = $('#' + opts.popupID).get(0).linked;
				if (element && element.tagName == 'SELECT') {
					var S = $(element);
					if ($('option[value=' + value + ']', S).size() == 0) {
						var Insert_before = $('option.' + ( opts.enable_choose ? opts.css_choose : opts.css_enter), S);
						var country = $('.LS-country', P).html();
						var name  = '';
						if (country) { name = name + country + ', '; }
						// если метро, то добавим город
						if (deep == 0) { 
							var city_name = $('.LS-head', P).html();
							if (city_name) { name = name + city_name + ', '; }
						}
						
						name = name + E.html();						
						
						Insert_before.before($('<option></option>').val(value).text(name));
					}
				}
				else if (element && element.tagName == 'INPUT') {
					var name = E.html();
					var country = $('.LS-country', P).html();
					if (country) { name = name + ', ' + country; }
					element.value = name;
				}
				CL_choose_cancel(value);
			}
			else if (deeper.length >= 3) {
				popup_fill(deeper[0], deeper[1], deeper[2], 0);
			}
			
			return false;
		}
		
		function change_deep() {
			
			var P	=  $('#' + opts.popupID);
			var lr	=  P.get(0).last_request;
			if (lr.select == 'metro') {
				popup_fill(lr.countryId, lr.regionId, 0, 0);
			}
			else if (lr.select == 'city') {
				popup_fill(lr.countryId, 0, 0, 0);
			}
			else if (lr.select == 'region') {
				popup_fill(0, 0, 0, 0);
			}
			else {
				
			}
					
			return false;
		}
		
		function popup_show(element) {
			var P = $('#' + opts.popupID);
			if (P.size() == 0) {
				$.ajax({
					'async'			: false,
					'url'			: opts.popupURL,
					'type'			: 'POST',
					'dataType'		: 'html',
					'success'		: function(r) {
						var popup = $(r).attr('id', opts.popupID).hide().appendTo('body');
						//$(document).keypress(popup_hide);
						popup.find('.close').unbind('click').click(popup_hide);
						popup.find('#LS-choose-button').click(make_selection);
						
						$('#' + opts.popupID).get(0).linked = element;
						popup_show(element);
					}
				});
				return true;
			}
			else if (P.is(':visible')) { return; }
			else {
				if ($('div#overlay').size() == 0) {	$('body').append('<div id="overlay" class="overlay"></div>');}
				var h = $('.ap-wrapper').height();
				$('#overlay').height(h).show();
				P.show();
				P.get(0).linked = element;
				$('.LS-country', P).hide();
				$('.LS-change-link', P).hide().unbind('click').click(change_deep);
				$('#LS-change-link', P).hide();
			}
		}
		
		function popup_hide(e) {
			if (e.type == 'keypress' && e.keyCode != 27) { return false; }
			CL_choose_cancel();
			return false;
		}
		
		
		function d(v) {
			return false;
			if (window.console && window.console.log) {
				window.console.log(v);
			}
		}
	};
})(jQuery);


var jsCore		= {
	getUniqId : function () {
		var id;
		var prefix = 'JSID_';
		do { id = prefix + Math.random().toString(16).replace(".", ""); } while( jQuery('#' + id).size() > 0 )
		
		return	id;
	},
	delegate:function(o,m){
		var ca=Array.prototype.slice.call(arguments,2);
		
		if(typeof(m)=='string') m=o[m];
		return function(){
			var a=[];
			a.push.apply(a,arguments);
			return m.apply(o,ca.concat(a))
		}
	}	
}

/**
 * SWFObject v1.5: Flash Player detection and embed - http://blog.deconcept.com/swfobject/
 *
 * SWFObject is (c) 2007 Geoff Stearns and is released under the MIT License:
 * http://www.opensource.org/licenses/mit-license.php
 *
 */
if( !window.SWFObject )
{
	if(typeof deconcept=="undefined"){var deconcept=new Object();}if(typeof deconcept.util=="undefined"){deconcept.util=new Object();}if(typeof deconcept.SWFObjectUtil=="undefined"){deconcept.SWFObjectUtil=new Object();}deconcept.SWFObject=function(_1,id,w,h,_5,c,_7,_8,_9,_a){if(!document.getElementById){return;}this.DETECT_KEY=_a?_a:"detectflash";this.skipDetect=deconcept.util.getRequestParameter(this.DETECT_KEY);this.params=new Object();this.variables=new Object();this.attributes=new Array();if(_1){this.setAttribute("swf",_1);}if(id){this.setAttribute("id",id);}if(w){this.setAttribute("width",w);}if(h){this.setAttribute("height",h);}if(_5){this.setAttribute("version",new deconcept.PlayerVersion(_5.toString().split(".")));}this.installedVer=deconcept.SWFObjectUtil.getPlayerVersion();if(!window.opera&&document.all&&this.installedVer.major>7){deconcept.SWFObject.doPrepUnload=true;}if(c){this.addParam("bgcolor",c);}var q=_7?_7:"high";this.addParam("quality",q);this.setAttribute("useExpressInstall",false);this.setAttribute("doExpressInstall",false);var _c=(_8)?_8:window.location;this.setAttribute("xiRedirectUrl",_c);this.setAttribute("redirectUrl","");if(_9){this.setAttribute("redirectUrl",_9);}};deconcept.SWFObject.prototype={useExpressInstall:function(_d){this.xiSWFPath=!_d?"expressinstall.swf":_d;this.setAttribute("useExpressInstall",true);},setAttribute:function(_e,_f){this.attributes[_e]=_f;},getAttribute:function(_10){return this.attributes[_10];},addParam:function(_11,_12){this.params[_11]=_12;},getParams:function(){return this.params;},addVariable:function(_13,_14){this.variables[_13]=_14;},getVariable:function(_15){return this.variables[_15];},getVariables:function(){return this.variables;},getVariablePairs:function(){var _16=new Array();var key;var _18=this.getVariables();for(key in _18){_16[_16.length]=key+"="+_18[key];}return _16;},getSWFHTML:function(){var _19="";if(navigator.plugins&&navigator.mimeTypes&&navigator.mimeTypes.length){if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","PlugIn");this.setAttribute("swf",this.xiSWFPath);}_19="<embed type=\"application/x-shockwave-flash\" src=\""+this.getAttribute("swf")+"\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\"";_19+=" id=\""+this.getAttribute("id")+"\" name=\""+this.getAttribute("id")+"\" ";var _1a=this.getParams();for(var key in _1a){_19+=[key]+"=\""+_1a[key]+"\" ";}var _1c=this.getVariablePairs().join("&");if(_1c.length>0){_19+="flashvars=\""+_1c+"\"";}_19+="/>";}else{if(this.getAttribute("doExpressInstall")){this.addVariable("MMplayerType","ActiveX");this.setAttribute("swf",this.xiSWFPath);}_19="<object id=\""+this.getAttribute("id")+"\" classid=\"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000\" width=\""+this.getAttribute("width")+"\" height=\""+this.getAttribute("height")+"\" style=\""+this.getAttribute("style")+"\">";_19+="<param name=\"movie\" value=\""+this.getAttribute("swf")+"\" />";var _1d=this.getParams();for(var key in _1d){_19+="<param name=\""+key+"\" value=\""+_1d[key]+"\" />";}var _1f=this.getVariablePairs().join("&");if(_1f.length>0){_19+="<param name=\"flashvars\" value=\""+_1f+"\" />";}_19+="</object>";}return _19;},write:function(_20){if(this.getAttribute("useExpressInstall")){var _21=new deconcept.PlayerVersion([6,0,65]);if(this.installedVer.versionIsValid(_21)&&!this.installedVer.versionIsValid(this.getAttribute("version"))){this.setAttribute("doExpressInstall",true);this.addVariable("MMredirectURL",escape(this.getAttribute("xiRedirectUrl")));document.title=document.title.slice(0,47)+" - Flash Player Installation";this.addVariable("MMdoctitle",document.title);}}if(this.skipDetect||this.getAttribute("doExpressInstall")||this.installedVer.versionIsValid(this.getAttribute("version"))){var n=(typeof _20=="string")?document.getElementById(_20):_20;n.innerHTML=this.getSWFHTML();return true;}else{if(this.getAttribute("redirectUrl")!=""){document.location.replace(this.getAttribute("redirectUrl"));}}return false;}};deconcept.SWFObjectUtil.getPlayerVersion=function(){var _23=new deconcept.PlayerVersion([0,0,0]);if(navigator.plugins&&navigator.mimeTypes.length){var x=navigator.plugins["Shockwave Flash"];if(x&&x.description){_23=new deconcept.PlayerVersion(x.description.replace(/([a-zA-Z]|\s)+/,"").replace(/(\s+r|\s+b[0-9]+)/,".").split("."));}}else{if(navigator.userAgent&&navigator.userAgent.indexOf("Windows CE")>=0){var axo=1;var _26=3;while(axo){try{_26++;axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash."+_26);_23=new deconcept.PlayerVersion([_26,0,0]);}catch(e){axo=null;}}}else{try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.7");}catch(e){try{var axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash.6");_23=new deconcept.PlayerVersion([6,0,21]);axo.AllowScriptAccess="always";}catch(e){if(_23.major==6){return _23;}}try{axo=new ActiveXObject("ShockwaveFlash.ShockwaveFlash");}catch(e){}}if(axo!=null){_23=new deconcept.PlayerVersion(axo.GetVariable("$version").split(" ")[1].split(","));}}}return _23;};deconcept.PlayerVersion=function(_29){this.major=_29[0]!=null?parseInt(_29[0]):0;this.minor=_29[1]!=null?parseInt(_29[1]):0;this.rev=_29[2]!=null?parseInt(_29[2]):0;};deconcept.PlayerVersion.prototype.versionIsValid=function(fv){if(this.major<fv.major){return false;}if(this.major>fv.major){return true;}if(this.minor<fv.minor){return false;}if(this.minor>fv.minor){return true;}if(this.rev<fv.rev){return false;}return true;};deconcept.util={getRequestParameter:function(_2b){var q=document.location.search||document.location.hash;if(_2b==null){return q;}if(q){var _2d=q.substring(1).split("&");for(var i=0;i<_2d.length;i++){if(_2d[i].substring(0,_2d[i].indexOf("="))==_2b){return _2d[i].substring((_2d[i].indexOf("=")+1));}}}return "";}};deconcept.SWFObjectUtil.cleanupSWFs=function(){var _2f=document.getElementsByTagName("OBJECT");for(var i=_2f.length-1;i>=0;i--){_2f[i].style.display="none";for(var x in _2f[i]){if(typeof _2f[i][x]=="function"){_2f[i][x]=function(){};}}}};if(deconcept.SWFObject.doPrepUnload){if(!deconcept.unloadSet){deconcept.SWFObjectUtil.prepUnload=function(){__flash_unloadHandler=function(){};__flash_savedUnloadHandler=function(){};window.attachEvent("onunload",deconcept.SWFObjectUtil.cleanupSWFs);};window.attachEvent("onbeforeunload",deconcept.SWFObjectUtil.prepUnload);deconcept.unloadSet=true;}}if(!document.getElementById&&document.all){document.getElementById=function(id){return document.all[id];};}var getQueryParamValue=deconcept.util.getRequestParameter;var FlashObject=deconcept.SWFObject;var SWFObject=deconcept.SWFObject;
	
	// by RubaXa
	var SWF	=
	{
		defParams: { allowScriptAccess: 'always', menu: false },
		
		
		build: function (id/*String*/, p/*Object*/)/*SWFNode*/
		{
			if( typeof id == 'string' )	id = jQuery( id );	// id
			if( id.append )	id	= id[0];	// jQuery
			if( !id.id ) id.id	= jsCore.getUniqId();
			id	= id.id;
			
			var
				  m	= p.movie/*MovieParams*/
				, v	= p.vars||{}/*FlashVars*/
				, p	= jQuery.extend(this.defParams, p.params)/*Params*/
				, fId
				, so	= new SWFObject(m.url, fId=(m.name||jsCore.getUniqId()), m.width||'100%', m.height||'100%', m.ver||m.version||'9', m.bg||m.bgColor||m.background)
				, k
			;
			
			for( k in v )	so.addVariable(k, encodeURIComponent( v[k] ));
			for( k in p )	so.addParam(k, p[k]);
			
			so.write(id);
			so = null;
			
			return	jQuery('#'+fId);
		}
	};
}

