
if (typeof moblli == 'undefined') {
	moblli = {};
}

moblli.dialog = {
    
	windowWidth: 0, // 0 - not use width in style attribute. Set it with CSS
    windowHeight: 0, // 0 - not use height in style attribute. Set it with CSS
    windowLeft: 0,
	windowTop: 0,
	windowContentHeight: 0,
	hMargin: 100,
	vMargin: 50,
	evalWindowWidth: 0,
	evalWindowHeight: 0,
	evalContentWidth: 0,
	evalContentHeight: 0,
	evalSpinnerHolderHeight: 0,
	zindex: 1000,
	modal: true,
	title: '',
	visible: false,	
	ready: false,
	title_on: true,
	
	defWidth: 0,
	defHeight: 'max',
	defHMargin: 100,
	defVMargin: 50,
	defModal: true,
	
	containerID: 'mobli_dialog',
	containerClass: 'modal',
	spinnerDOM: '\'<div style="\'+styleAttr+\'"><div class="pop_spinner_holder" style=""><img src="/images/loader.gif" width="66" height="66" style="margin:0px auto;display:block;" /><div style="padding-top:15px;">Loading... Please Wait...</div></div></div>\'',
	dialogDOM: '\'<div class="\'+this.containerClass+\'" id="\'+this.containerID+\'" style="\'+styleAttr+\'"><div class="pop_wrap">\'+titleAttr+\'<div class="pop_cont_box"><div class="pop_cont_scroll" style="">\'+contentStr+\'</div></div></div></div>\'',
	titleDOM: '<p class="pop_title"><span class="pop_title_capture">\'+titleStr+\'</span><a href="javascript:moblli.dialog.close();" id="closeme">Close</a></p>',
	
	tabsDOM: '<div id="pop_cont_tabs" class="double_tab"></div>',
	tabs: null,
	tabs_active: 0,
	
	buttonsDOM: '<div id="pop_bot_closer" class="cleaner"></div>',
	buttons: null,
	filter_fn: null,
	filter_obj: null,
	filter_timeout_handler: 0,
	filter_interval: 500,
	
	initTabs: function(tabs, filter_fn, active, tabs_class) {
		
		this.filter_fn = ( typeof(filter_fn) != 'undefined' && filter_fn != null) ? filter_fn : null;
		if( typeof(filter_fn) != 'undefined' && filter_fn != null) {
			this.filter_obj = filter_fn;
			this.filter_fn = function() {
				
				if( moblli.dialog.filter_timeout_handler )
				{
					clearTimeout(moblli.dialog.filter_timeout_handler);
				}
				var dch = (moblli.dialog.filter_obj.url.indexOf('?')==-1) ? '?' : '&';
				var exe = "$('#"+moblli.dialog.filter_obj.update+"').load('"+moblli.dialog.filter_obj.url+dch+"filter="+( moblli_url_encode($('#filter_val').val()) )+"');";
				//var exe_test = 'alert("'+exe+'")';
				$('#'+moblli.dialog.filter_obj.update).html(moblli.dialog.getDefaultSpinner());
				moblli.dialog.filter_timeout_handler = setTimeout(exe, moblli.dialog.filter_interval);
			};
		}
		else {
			
			this.filter_fn = null;
		}
		
		
		this.tabs_active = ( typeof(active) != 'undefined') ? parseInt(active) : 0;
		
		if(tabs.length || this.filter_fn!=null) {
			
			this.tabs = tabs;
			$('#'+this.containerID+' .pop_cont_box').prepend(this.tabsDOM);
			this.windowContentHeight -= $('#pop_cont_tabs').outerHeight();
			$('#'+this.containerID+' div.pop_cont_scroll').css("max-height", this.windowContentHeight+"px");
			if( typeof(tabs_class) != 'undefined') {
				if(tabs_class) {
					$('#pop_cont_tabs').addClass(tabs_class);
				}
			}
		}
		
		if(tabs.length) {

			var new_tab, class_str, fltr_style, new_fltr, dch, use_tabs_filters=false;
			for(var i in this.tabs) {
				
				if(i==this.tabs_active) {
					
					class_str = ' class="current"';
					$('#'+this.tabs[i].content_id).show();
				}
				else
				{
					class_str = '';
					$('#'+this.tabs[i].content_id).hide();
				}
				
				new_tab = '<a' + class_str + ' id="tab_but_' + i + '" href="javascript:void(0);" onclick="moblli.dialog.activateTab(' + i + ');return false;">' + this.tabs[i].caption + '</a>';				
				$('#pop_cont_tabs').append(new_tab);
				
				if( typeof(this.tabs[i].filter) != 'undefined' && this.tabs[i].filter!=null )
				{
					use_tabs_filters=true;
					fltr_style = (class_str) ? '' : ' style="display:none;"';
					dch = (this.tabs[i].filter.url.indexOf('?')==-1) ? '?' : '&';
					
					this.tabs[i].fltr_html = '<input onkeyup="if(moblli.dialog.filter_timeout_handler) {clearTimeout(moblli.dialog.filter_timeout_handler);};';
					this.tabs[i].fltr_html+= '$(\'#' + this.tabs[i].filter.update + '\').html(moblli.dialog.getDefaultSpinner());';
					this.tabs[i].fltr_html+= 'moblli.dialog.filter_timeout_handler = setTimeout(function(){';
					this.tabs[i].fltr_html+= '$(\'#' + this.tabs[i].filter.update + '\').load( \'' + this.tabs[i].filter.url + dch + 'filter=\' + (moblli_url_encode( $(\'#filter_val_' + i + '\').val() )) )';
					this.tabs[i].fltr_html+= '},'+this.filter_interval+');"';
					this.tabs[i].fltr_html+= ' type="text" value="" id="filter_val_' + i + '" name="filter_val_' + i + '" ' + fltr_style + ' />';

				}
			}
			
			if(use_tabs_filters)
			{
				$('#pop_cont_tabs').append( '<div id="filter_field"></div>' );
				for(var i in this.tabs) {
					
					$('#filter_field').append( this.tabs[i].fltr_html );
				}
			}
		}
		
		if(this.filter_fn!=null)
		{
			var filter_html = '<div id="filter_field"><input type="text" value="" id="filter_val" name="filter_val" /></div>';
			
			$('#pop_cont_tabs').append(filter_html);
			$('#filter_val').keyup(this.filter_fn);
		}
	},
	
	removeTabs: function() {
		this.tabs=null;
		this.tabs_active=0;
		this.windowContentHeight += $('#pop_cont_tabs').outerHeight();
		$('#pop_cont_tabs').remove();
		$('#'+this.containerID+' div.pop_cont_scroll').css("max-height", this.windowContentHeight+"px");
	},
	
	activateTab: function(tab_id) {
		
		$('#tab_but_' + this.tabs_active).removeClass('current');
		$('#tab_but_' + tab_id).addClass('current');
		$('#' + this.tabs[this.tabs_active].content_id).hide();
		$('#' + this.tabs[tab_id].content_id).show();
		
		$('#filter_val_' + this.tabs_active).hide();
		$('#filter_val_' + tab_id).show();
		this.tabs_active = tab_id;
	},
	
	initButtons: function(buttons) {

		if(buttons.length) {
			
			this.buttons = buttons;
			$('#'+this.containerID+' .pop_cont_box').append(this.buttonsDOM);
			this.windowContentHeight -= $('#pop_bot_closer').outerHeight();
			$('#'+this.containerID+' div.pop_cont_scroll').css("max-height", this.windowContentHeight+"px");
			
			var new_button, sl_fn, attr_str;
			for(var i in this.buttons) {
				
				attr_str = '';
				if( typeof(this.buttons[i].attributes)!='undefined' ) {
					for(var at in this.buttons[i].attributes) {
						
						attr_str += ' '+at+'="'+this.buttons[i].attributes[at]+'"';
					}
				}
				new_button = '<a' + attr_str + ' href="javascript:void(0);" onclick="' + this.buttons[i].fn + ';return false;">' + this.buttons[i].caption + '</a>';
				$('#pop_bot_closer').append(new_button);
			}			
		}
	},
	
	removeButtons: function() {
		this.buttons=null;
		this.windowContentHeight += $('#pop_bot_closer').outerHeight();
		$('#pop_bot_closer').remove();
		$('#'+this.containerID+' div.pop_cont_scroll').css("max-height", this.windowContentHeight+"px");
	},

	yo: function() {
		
		var debug_info = 'Debug Info:\n';
		debug_info += '\n' + 'viewportWidth=' + $(window).width();
		debug_info += '\n' + 'viewportHeight=' + $(window).height();
		debug_info += '\n' + 'windowWidth=' + this.windowWidth;
		debug_info += '\n' + 'windowHeight=' + this.windowHeight;
		debug_info += '\n' + 'windowLeft=' + this.windowLeft;
		debug_info += '\n' + 'windowTop=' + this.windowTop;
		debug_info += '\n' + 'hMargin=' + this.hMargin;
		debug_info += '\n' + 'vMargin=' + this.vMargin;
		debug_info += '\n' + 'evalWindowWidth=' + this.evalWindowWidth;
		debug_info += '\n' + 'evalWindowHeight=' + this.evalWindowHeight;
		debug_info += '\n' + 'evalContentWidth=' + this.evalContentWidth;
		debug_info += '\n' + 'evalContentHeight=' + this.evalContentHeight;
		debug_info += '\n' + 'evalSpinnerHolderHeight=' + this.evalSpinnerHolderHeight;
		
		alert( debug_info );
	},
	
    init: function() {

        this.setProperties();
        var dialogDOM = this.getDialogDOM();
        $('body').append(dialogDOM);
        this.ready = true;
        
        $(window).resize(function() { moblli.dialog.windowResize(); });
    },
    
    open: function(params) {
    	
		var modal = this.defModal;
		var title = '';
		var width = this.defWidth;		
		var hMargin = this.defHMargin;		
		var height = this.defHeight;		
		var vMargin = this.defVMargin;
		var title_on = this.title_on;
		
		if( typeof(params) != 'undefined' ) {
    		
			if( typeof(params.modal) != 'undefined' ) { modal = params.modal; }
			if( typeof(params.title) != 'undefined' ) { title = params.title; }
			if( typeof(params.width) != 'undefined' ) { width = params.width; }		
			if( typeof(params.hmargin) != 'undefined' ) { hMargin = params.hmargin; }	
			if( typeof(params.height) != 'undefined' ) { height = params.height; }		
			if( typeof(params.vmargin) != 'undefined' ) { vMargin = params.vmargin; }
			if( typeof(params.title_on) != 'undefined' ) { title_on = params.title_on; }
    	}    	
		
    	this.setProperties(width, hMargin, height, vMargin, modal, title_on);
		this.resetDOM();
		this.setContent(this.getDefaultSpinner());
		this.setTitle(title);
    	this.show();
   		this.updateContentHeight(this.containerID);
    },
      
	resetDOM: function() {
		
		this.ready = false;
		$('#'+this.containerID).remove();
		$('.pop_overlay').remove();
		var dialogDOM = this.getDialogDOM();
		$('body').append(dialogDOM);
		this.ready = true;
	},
	
	windowResize: function() {
		this.updateCenter();
    	$('.pop_overlay').css({'width': $(document).width() + 'px', 'height' : $(document).height() + 'px'});
	},
    
	setProperties: function(width, hMargin, height, vMargin, modal, title_on) {

		width = typeof(width) != 'undefined' ? width : this.defWidth;
		hMargin = typeof(hMargin) != 'undefined' ? hMargin : this.defHMargin;		
		height = typeof(height) != 'undefined' ? height : this.defHeight;
		vMargin = typeof(vMargin) != 'undefined' ? vMargin : this.defVMargin;		
		modal = typeof(modal) != 'undefined' ? modal : this.defModal;
		title_on = typeof(title_on) != 'undefined' ? title_on : this.title_on;
		
    	this.setWidth(width, hMargin);
    	this.setHeight(height, vMargin);
    	this.modal = modal;
    	this.title_on = title_on;
    	
        this.resetEvaluatedDims();
        this.setCenter();
	},
    
    show: function() {
		
    	this.visible = true;
    	$('#'+this.containerID).show();
		if(this.modal) {
			var oh = $(document).height();
			$('.pop_overlay').css('height', oh+'px');
			$('.pop_overlay').show();
		}
	},
    
	hide: function() {
		
		this.visible = false;
		$('#'+this.containerID).hide();
		$('.pop_overlay').hide();
	},
    
	close: function() {
		
		this.hide();
		this.setContent(this.getDefaultSpinner());
	},
    
    getSpinner: function(styleAttr) {
		
		styleAttr = typeof(styleAttr) != 'undefined' ? styleAttr : 'margin:0px auto;text-align:center;';		
		return eval(this.spinnerDOM);
	},
	
	getDefaultSpinner: function() {
		
		var vMargin = (this.evalContentHeight && this.evalSpinnerHolderHeight) ? parseInt( (this.evalContentHeight-this.evalSpinnerHolderHeight)/2 ) : 0;
		
		styleAttr = 'margin:'+vMargin+'px auto;text-align:center;';		
		return eval(this.spinnerDOM);
	},
	
	getTestDialogDOM: function(ID, styleAttr, titleStr, contentStr) {
		
		titleStr = typeof(titleStr) != 'undefined' ? titleStr : ' ';
		contentStr = typeof(contentStr) != 'undefined' ? contentStr : ' ';
		var scrollHeight = 'auto';
    
    var titleAttr = '';
    if (this.title_on) {
      titleAttr = this.titleDOM;
    }
		
		var dialogDOM = eval(this.dialogDOM);
		return dialogDOM.replace('id="'+this.containerID+'"', 'id="'+ID+'"');
	},
	
	getDialogDOM: function(titleStr, contentStr) {

	    var titleAttr = '';
	    if (this.title_on) {
	      titleAttr = this.titleDOM;
	    }

		var scrollHeight = this.windowContentHeight + 'px';
		var styleAttr = this.getSizesStylePart(true) + 'position:fixed;left:' + this.windowLeft + 'px;top:' + this.windowTop + 'px;display:none;z-index:' + this.zindex + ';';
		//var overlay = '<div class="pop_overlay" style="width:' + $(document).width() + 'px;height:' + $(document).height() + 'px;display:none;position:absolute;top:0px;left:0px;z-index:' + (this.zindex-1) + ';"><!--//--></div>';
		var overlay = '<div class="pop_overlay" style="display:none;position:fixed;top:0px;left:0px;z-index:' + (this.zindex-1) + ';"><!--//--></div>';
		
		titleStr = typeof(titleStr) != 'undefined' ? titleStr : ' ';
		contentStr = typeof(contentStr) != 'undefined' ? contentStr : this.getDefaultSpinner();
		
		return eval(this.dialogDOM) + overlay;
	},
	
	getSizesStylePart: function(no_height) {
		
		no_height = typeof(no_height) != 'undefined' ? no_height : false;
		var sizeStyle = '';
		if(this.windowWidth) {
			sizeStyle+='width: '+this.windowWidth+'px;';
		}
		if(this.windowHeight && !no_height) {
			sizeStyle+='height: '+this.windowHeight+'px;';
		}
		return sizeStyle;
	},
	
    setTitle: function(title) {
    	this.title = title;
    	$('#'+this.containerID+' p.pop_title span.pop_title_capture').html(title);
    },
    
    setContent: function(content) {
    	$('#'+this.containerID+' div.pop_cont_scroll').html(content);
    },
    
    setWidth: function(width, hMargin) {
    	
    	hMargin = typeof(hMargin) != 'undefined' ? hMargin : this.hMargin;
    	this.hMargin = hMargin;
    	var maxWidth = $(window).width()-2*hMargin;

    	switch( typeof(width) ) {
    	
    	case 'number':
    		this.windowWidth = (width<0 || width>maxWidth) ? 0 : parseInt(width);
    		break;
    	case 'string':
    		this.windowWidth = (width=='max') ? maxWidth : 0;
    		break;
    	default:
    		this.windowWidth = 0;
    	}
    },
    
    setHeight: function(height, vMargin) {
    	
    	vMargin = typeof(vMargin) != 'undefined' ? vMargin : this.vMargin;
    	this.vMargin = vMargin;
    	var maxHeight = $(window).height()-2*vMargin;

    	switch( typeof(height) ) {
    	
    	case 'number':
    		this.windowHeight = (height<0 || height>maxHeight) ? 0 : parseInt(height);
    		break;
    	case 'string':
    		this.windowHeight = (height=='max') ? maxHeight : 0;
    		break;
    	default:
    		this.windowHeight = 0;
    	}
    },
    
    updateCenter: function() {
    	this.setCenter();
    	$('#'+this.containerID).css({'left': this.windowLeft + 'px', 'top' : this.windowTop + 'px'});
    },
    
    setCenter: function() {
    	
    	this.windowLeft = parseInt(($(window).width() - this.evalWindowWidth)/2);
    	this.windowTop = parseInt(($(window).height() - this.evalWindowHeight)/2);
    },
    
    resetEvaluatedDims: function() {
        
    	var evalDims = this.evaluateDims();

        this.evalWindowWidth = evalDims.windowWidth;
        this.evalWindowHeight = evalDims.windowHeight;
        this.evalContentHeight = evalDims.contentHeight;
        this.evalContentWidth = evalDims.contentWidth;
        if( evalDims.spinnerHeight ) {
        	this.evalSpinnerHolderHeight = evalDims.spinnerHeight;
        }
    },
    
    updateContentHeight: function(ID) {
    	
    	var wrapMarg = $('#'+ID+' div.pop_wrap').outerHeight() - $('#'+ID+' div.pop_wrap').height();
    	var ttlSize = $('#'+ID+' p.pop_title').outerHeight();
    	var contWrapMarg = $('#'+ID+' div.pop_cont_box').outerHeight() - $('#'+ID+' div.pop_cont_box').height();
    	var contMarg = parseInt($('#'+ID+' div.pop_cont_scroll').css("padding-top")) + parseInt($('#'+ID+' div.pop_cont_scroll').css("padding-bottom")) + parseInt($('#'+ID+' div.pop_cont_scroll').css("margin-top")) + parseInt($('#'+ID+' div.pop_cont_scroll').css("margin-bottom"));
    	
    	this.windowContentHeight = this.windowHeight - wrapMarg - ttlSize - contWrapMarg - contMarg;
    	$('#'+ID+' div.pop_cont_scroll').css("max-height", this.windowContentHeight+"px");
    },
    
    evaluateDims: function() {
    	
    	var testerID = (this.visible && this.ready) ? this.containerID : this.containerID+'_test';
    	
    	if(!this.visible || !this.ready) {
    		var tester_cont = '<img src="/images/spacer.gif" alt="" width="1" height="2000" />';    		
    		var dialogDOM = this.getTestDialogDOM( testerID, this.getSizesStylePart() + 'position:absolute;top:-10000px;left:-10000px;display:block;', 'Test', tester_cont);
    		$('body').append(dialogDOM);
    		this.updateContentHeight(testerID);
    		$('#'+testerID+' div.pop_cont_scroll').css("height", this.windowContentHeight+"px");
    	}

    	var w=$('#'+testerID).innerWidth();
    	var h=$('#'+testerID).innerHeight();
    	var cw=$('#'+testerID+' div.pop_cont_scroll').width();
    	var ch=$('#'+testerID+' div.pop_cont_scroll').height();
    	
    	if(!this.ready) {
    		var spinner = this.getSpinner();
    		$('#'+testerID+' div.pop_cont_scroll').html(spinner);
    	}
    	
    	var sh = ( $('#'+testerID+' div.pop_spinner_holder').size() ) ? $('#'+testerID+' div.pop_spinner_holder').outerHeight() : 0;
    	
    	// CSS Bug workaround:
    	//sh += parseInt($('#'+testerID+' div.pop_cont_scroll').css("margin-top")) + parseInt($('#'+testerID+' div.pop_cont_scroll').css("margin-bottom")) + parseInt($('#'+testerID+' div.pop_cont_scroll').css("padding-top")) + parseInt($('#'+testerID+' div.pop_cont_scroll').css("padding-bottom"));
    	
    	if(!this.visible || !this.ready) {
    		$('#'+testerID).remove();
    	}
    	
    	return { windowWidth: w, windowHeight: h, contentWidth: cw, contentHeight: ch, spinnerHeight: sh };
    }
    
};

$(document).ready(function()
{
	moblli.dialog.init();
});

var moblli_last_call = null;
var moblli_last_cont = null;
var moblli_last_selector = null;

function moblli_char_encode(c)
{
	return '%' + c.charCodeAt(0).toString(16);
}

function moblli_url_encode(url)
{
	return encodeURIComponent(url).replace( /\%20/g, '+' ).replace( /[!'()*~]/g, moblli_char_encode );
}

function moblli_buffer_last_call(obj, event)
{
	event = ( typeof(event) != 'undefined' ) ? event : 'click';
	moblli_last_call =  $(obj).attr('on'+event);
}

function moblli_buffer_last_cont(selector)
{
	moblli_last_cont = $('#'+selector).html();
	moblli_last_selector = selector;
}

function moblli_run_last_call()
{
	var buffer_type = typeof(moblli_last_call);
	if( buffer_type.toLowerCase() == 'function' )
	{
		moblli_last_call.apply();
		moblli_last_call = null;
	}
}

function moblli_retrive_from_backup()
{
	if(moblli_last_cont!=null && moblli_last_selector!=null)
	{
		$('#'+moblli_last_selector).html(moblli_last_cont);
		moblli_last_cont = moblli_last_selector = null;
	}
}

function start_overlay_tabs() {
    $('#followers_but').click(function(){

    	$('#followers_but').addClass('current');
    	$('#followed_but').removeClass('current');
    	$('#followers_list').show();
    	$('#followed_list').hide();
    });
    $('#followed_but').click(function(){
    	$('#followers_but').removeClass('current');
    	$('#followed_but').addClass('current');
    	$('#followers_list').hide();
    	$('#followed_list').show();
     });
}

function user_toggle_selection(id) {
	$('#followers_' + id + ' .extra .select').toggleClass('on');
	$('#followed_' + id + ' .extra .select').toggleClass('on');
}

function submit_share_request(subj_type, subj_id) {
	
	var selected = new Array();
	
	if( $('.m_item .extra .select.on').size() ) {
		
		var selected_inv = new Array();
		$('.m_item .extra .select.on').each(function(){ 
				var id_attr = $(this).closest('.m_item').attr('id'); 
				var tmp = id_attr.split('_');
				selected_inv[ parseInt(tmp[1]) ] = parseInt(tmp[1]); 
			});
		
		for(var i in selected_inv)
		{
			selected.push(i);
		}
	}
	
	moblli.dialog.setContent(moblli.dialog.getDefaultSpinner());
	jQuery.ajax({
		type:'POST',
		dataType:'html',
		data: ({module_name:'module_share',module_action:'process',subj_type:subj_type,subj_id:subj_id,'selected[]':selected}),
		success:function(data, textStatus){ moblli.dialog.setContent(data); },
		url:'/overlay_module'
	}); 
	
	return false;
}


