var entity_id = 0;
var entity_ids = [];
var entity_type = 1;
var ent_selected = 0;
var select_type = 0;
var enableGMap = 0;
//var srchRes;
var muncs;
var prvcs;
var wtchs;
var locale = 'en';
var langWords = Array();
var srch_str;
var current_page = '';
//window setings
var foothead_height = 45+100;
var tabs_header_h = 25;
var min_wind_height = 800;
var lm_sel_ent_count = 12; // this is means height must be 280px. 12*15+100 = 280 
var lm_min_h_most_sh_pages = 200;
var lm_min_h_lmb = 130;
var lm_min_h_party_list = 200;
var lm_min_h_p = 70;
var lm_min_h_rel_links = 100;
var lm_min_h_rl = 50;
var root_url = 'http://'+location.host+location.pathname;

function embedVoteFlash(miid){
	var embed = document.getElementById('embed_container_'+miid).innerHTML;
	var includes = '<script type="text/javascript" src="http://'+location.host+'/js/AC_OETags.js" ></script>';
	includes += '<script type="text/javascript" src="http://'+location.host+'/js/history.js" ></script>';
	includes += '<script type="text/javascript" src="http://'+location.host+'/js/voteflash.js" ></script>';
	document.getElementById('emb_text_'+miid).value = includes+embed;
	
}

function entSelSelecting(params){

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

    var select_type = 0;
	if (params.select_type) select_type = params.select_type; 
	if (params.entity_ids) params.entity_ids = params.entity_ids; else params.entity_ids = [];
	
	switch (select_type){
		//on search methods pages
		case '2':
		case 2:
            var ents = '';
            if (params.entity_ids.length > 0 ){
                ents = '/entiteiten:'+params.entity_ids.join(',')+'/';
            }
			var _href = document.location.href;
            _href = _href.split('?');
            _href = rtrim(_href[0].replace( /(\/?entiteiten:[,0-9]+\/?)/,''),'/')+ ents;// + ( _href[1]? '?'+_href[1] : '');

			document.location =  _href;
			break;
		//on map page 
		case '1':
		case 1:

			break;
		//on speaker,meeting,party,blogarticle pages
		case '0':
		case 0:
		default:
			document.location = 'http://'+location.host;
			break;	
	}
}

function removeZero(arr){
	var ind = arr.indexOf('0'); 
	if (ind >= 0){
		arr.splice(ind,1);
	}
	return arr;
}

function resizeMainLeftMenu() {
	var tabHeight   = getMainContentHeight();

    var header_h    = $(".leftMenuHead").innerHeight();
    var content_h   = $(".leftMenuContent").innerHeight();
    var free_h      =  tabHeight - header_h - content_h;
    var height, scroll_msp_h, scroll_h;

   if (free_h > 0){
        height = getElementHeight("tab1_scroll_msp");
        if(height){
            scroll_msp_h 	= Math.min( height+free_h, getElementHeight("tab1_list_msp"));

            $("#tab1_scroll_msp").css("height",scroll_msp_h);
        }
    }else if( free_h<0) {
        height = getElementHeight("tab1_scroll_msp");
        if(height){
            scroll_h 		= Math.max( height+free_h, lm_min_h_most_sh_pages);

            $("#tab1_scroll_msp").css("height",scroll_h);
        }
    }

//	view with selected entity
	resizeEntityInfo(tabHeight);
	
	
}

function resizeMainRightMenu() {
	$(document).ready(function() {

		var mcont_h	= getMainContentHeight();
		var rmh_wtwitts = mcont_h - $("#rm_twitter_content").height() ;

		var blocks 	= [];
		if ($('#rm_pagerl_content').size()) blocks.push('rm_pagerl');
		if ($('#rm_blogs_content').size()) blocks.push('rm_blogs');
		if ($('#rm_entrl_content').size()) blocks.push('rm_entrl');

			for (var bl in blocks) {
				
				var free_h = rmh_wtwitts;
				for (var fhbl in blocks) {
					 free_h	-= $("#"+blocks[fhbl]+"_content").innerHeight();
				}
				
				var block 			= $("#" + blocks[bl] + "_content");
				
				if (block.size()) {
					var block_scroll = $("#" + blocks[bl] + "_scroll");
					
					if (block_scroll.offset().top && block.offset().top) {
						var oftop1 = block_scroll.offset().top ||0;
						var oftop2 = block.offset().top || 0;
						var blscrl_postop =  oftop1 - oftop2 - 0;
					}
					var block_cont_h = $("ul", block_scroll).height() + blscrl_postop;
					var h_per_bl = rmh_wtwitts / blocks.length;
					
					if (free_h < 0) {
						var new_blh = Math.max(h_per_bl, block.innerHeight() + free_h);
						
						if (new_blh > 60 && new_blh < block_cont_h) {
							block.height(new_blh-blscrl_postop);
							block_scroll.height(new_blh-blscrl_postop);
						}
					}else if (free_h>0){
						var new_blh = Math.min(block_cont_h, block.innerHeight() + free_h);
						block.height(new_blh);
						block_scroll.height(new_blh);
					}
				}
			}
	
	});
}

function resizeEntityInfo(tabHeight) {

	var cont_sm_h 	= $(".leftMenuHead").innerHeight();
	var cont_p_h 	= getElementHeight("cont_p");
	var cont_lmb_h 	= getElementHeight("cont_lmb");

    var free_h, height, scroll_h;
	
	if (cont_sm_h>0 && cont_p_h>0 && cont_lmb_h>0 ){
		free_h = tabHeight - cont_sm_h-cont_p_h-cont_lmb_h;

		if (free_h > 0){
			scroll_h 	= Math.min(getElementHeight("scroll_p")+free_h, getElementHeight("list_p"));
			
			$("#scroll_p").css("height",Math.max( scroll_h, lm_min_h_p));
			
			cont_p_h 	= getElementHeight("cont_p");
			
		}else if (free_h<0){
			height = getElementHeight("scroll_lmb");
			
			if(height){
				
				scroll_h 	= Math.max( height+free_h, lm_min_h_lmb);
			
				$("#scroll_lmb").css("height",scroll_h);
				
				cont_lmb_h 	= getElementHeight("cont_lmb");
			}
			
		}
		
		free_h = tabHeight - cont_sm_h-cont_p_h-cont_lmb_h;
		
		if (free_h > 0){
			scroll_h 	= Math.min(getElementHeight("scroll_lmb")+free_h, getElementHeight("list_lmb"));
			
			$("#scroll_lmb").css("height",Math.max( scroll_h, lm_min_h_lmb));
		
		}else if (free_h<0){
			height = getElementHeight("scroll_p");
			
			if(height){
				
				scroll_h 	= Math.max( height+free_h, lm_min_h_p);
			
				$("#scroll_p").css("height",scroll_h);
				
				cont_p_h 	= getElementHeight("cont_p");
			}
			
		}
	}

}

function resizeFlashMap(){

    var cntnr   =  $(".pa_map");
    var lft     = cntnr.offset().left - $("#container").offset().left;
    var fmm_h   = $("#mapFlashMsg").innerHeight();
    $("#entitiesMapContainer").css( {height: cntnr.innerHeight() - fmm_h, width: cntnr.innerWidth(), left: lft} );
    
}

function selectEntity(params){
	
	var _entity_ids     = [];
	var _entity_id      = 0;
	var _select_type    = select_type || 0;
	
	if ( typeof( params ) == 'undefined' )params = {};
	if (params.select_type != null) _select_type = params.select_type;
	if (params.entity_id) _entity_id = params.entity_id;
	if (params.entity_ids) _entity_ids = params.entity_ids;
	
	if (_entity_ids.length == 0 && _entity_id > 0)
		_entity_ids.push(_entity_id);
	
//	saveEntIds(_entity_ids);
	$.post(root_url,
			{page:"main",
      		  action:"saveEntIds",
      		  async:1,
      		  "eids[]":_entity_ids
      	  },
      	  function (data){
      		entSelSelecting({"select_type":_select_type,"entity_ids":_entity_ids});
      	  }
	  	);
	
}

function show_entinfo(params){
	var _epid 		= '';
	var _mid 		= '';
	var _entity_id 	= entity_id;
	var select_type = 0;
	var _etype 		= entity_type;
	
	if ( typeof( params ) == 'undefined' )params = {};
	if (params.select_type) select_type = params.select_type;
	if (params.entity_id) _entity_id 	= params.entity_id;
	if (params.etype) _etype 			= params.etype;
	
	if ( typeof( epid ) != 'undefined' ) _epid = epid;   
	if ( typeof( mid ) != 'undefined' ) _mid = mid;   
	

    if (_entity_id > 0){
	
		$.post(
	      	  root_url,{
	      		  page:"main",
	      		  action:"entinfo",
	      		  async:1,
	      		  eid:_entity_id,
	      		  cpage:current_page,
	      		  mid:_mid,
	      		  epid:_epid,
	      		  'select_type':select_type
	      		  
	      	  },
	      	  function (data){
    		  
                  $('.leftMenuContent').html(data);
	      		  resizeMainLeftMenu();
	      	  }
	  	  
	  	);
	}

}

function saveEntityId(entity){
	
	var eids = [];
	eids = $("#"+entity.id).val();

	if (typeof eids == 'string' || typeof eids == 'number') 
		eids = [eids];
	else if (typeof eids == 'undefined') 
		eids = [0];
	
	entity_ids = eids;

	if (eids.length == 1 ){
		entity_id = eids[0];
	}else 
		entity_id = 0;
}


function subm_search_form() {
	document.search_form.submit();
}
function new_search_srchform() {
	$("#pg").val(1);
	subm_search_form();
}

function showPage(pg){
	document.getElementById('pg').value = pg;
	subm_search_form();
}

function setHideSF() {
	$("#hide_show_sf").val('1');
}
function setHideSlowSF() {
	$("#hide_show_sf").val('2');
}

function getMainContentHeight(){
	
	var mySize = getClientWindSize();
	var myHeight = min_wind_height;
	if (mySize[1]>min_wind_height) 
		myHeight = mySize[1];
	myHeight = myHeight -getElementHeight("header")-getElementHeight("container_footer") - 
		getElementHeight('headerbar')- getElementHeight('container_buttom_border');

	return myHeight;
}

function getMainContentBodyHeight(){

	var myH = document.body.offsetHeight;
	
    var myHeight = Math.max(myH, min_wind_height);
    
	myHeight = myHeight -getElementHeight("header")-getElementHeight("container_footer") -
		getElementHeight('headerbar')- getElementHeight('container_buttom_border');

	return myHeight;
}

function getSelectedEidsFromForm(){
	var _eids = [];
	$("[name=eids[]]").each(function(){
		_eids.push($(this).val());
	});
	return _eids;
}

function getEidSelTypeLeftMenu(){
	var _eid = 0;
//	enttype_selent

	//get selected entities from component entityInfo
	var sel_ent = $("#tab_"+entity_type+" > #cont_sm > input[name=enttype_selectent]");
	
	if (sel_ent.size() > 0){
		_eid = sel_ent.val() || 0;
	}
	
	return _eid;
}

function getTimeFirstVisibleMin(){
	var jmp_time = 0; 
	var jmp_name =  $('.minute_jump:visible').attr('name');
	if (jmp_name) jmp_time = jmp_name.replace( /(fpj_)/,'');
	return jmp_time;
}


function directLinkParseSearchForm(){
    var result = '';
    var _href = location.href.split('?');
    $('#search_form input, #search_form select').each(function(){

        var elem = parseFormElement(this);
        if (elem.value)
            result += '&'+elem.name+'='+elem.value;
    });

    return _href[0]+'?'+result;
}
function fetchSearchFormData(){
    var sform               = $("#search_form");
    var eids                = [];
    var srcphrase           = '';
    var commissions         = [];
    var parties             = [];
    var speakers            = [];
    var themes              = [];
    var period              = {'from':'','till':''};
    var sort_order          = '';
    var votdisu             = '';
    var votprtdisu          = '';

    $('[name^="eids"]',sform).each(function(){
        eids.push( this.value );
    });

    if ( $("#chbox_commissions:checked").val() ){
        $('[id^="cb_commission_"]:checked',sform).each(function(){
            commissions.push( $('label[for="'+this.id+'"]',sform).text() );
        });
    }

    if ( $("#chbox_parties:checked").val() ){
        if ( $("#parties").size() ){
            $('#parties option:selected',sform).each(function(){
                parties.push( $(this,sform).text() );
            });
        }else{
            $('[id^="cb_party_"]:checked',sform).each(function(){
                parties.push( $('label[for="'+this.id+'"]',sform).text() );
            });
        }
    }

    if ( $("#chbox_speakers:checked").val() ){
        if ( $("#speakers").size() ){
            $('#speakers option:selected',sform).each(function(){
                speakers.push( $(this,sform).text() );
            });
        }else{
            $('[id^="cb_speaker_"]:checked',sform).each(function(){
                speakers.push( $('label[for="'+this.id+'"]',sform).text() );
            });
        }
    }
    
    if ( $("#chbox_themes:checked").val() ){
        $('[id^="cb_theme_"]:checked',sform).each(function(){
            themes.push( $('label[for="'+this.id+'"]',sform).text() );
        });
    }

    if ( $("#chbox_srcphrase:checked").val() ) srcphrase = $('#srcphrase',sform).val() ;

    if ( $("#chbox_period:checked").val() ) {
        period.from         = $('#period_from',sform).val();
        period.till         = $('#period_till',sform).val();
    }
    sort_order              = $('#sort_opt option:selected ',sform).text();
    votdisu                 = $('#chbox_votdisu:checked',sform).val();
    votprtdisu              = $('#chbox_votprtdisu:checked',sform).val();


    return { 'eids':eids, 'commissions':commissions, 'themes':themes,  'srcphrase':srcphrase, 'period':period,
        'sort_order':sort_order, 'votdisu':votdisu, 'votprtdisu':votprtdisu, 'parties':parties,
        'speakers':speakers };
}

function callFetchSearchFormData(){
    var srch_params_str=$.base64.encode(JSON.stringify(fetchSearchFormData()));
    $('#search_params_string').val(srch_params_str);
}

