var rslt = navigator.appVersion.match(/MSIE (\d+\.\d+)/, '');
var is_ie6 =(rslt != null && (Number(rslt[1]) < 7));
var is_ie7 =(rslt != null && (Number(rslt[1]) >= 7));
var is_ie = ((navigator.appVersion.match(/\bMSIE\b/))?true:false);
var is_safari = ((navigator.appVersion.match(/\bSafari\b/))?true:false);
var is_firefox = ((navigator.userAgent.toLowerCase().match(/\bfirefox\b/))?true:false);

function display_div(id) {
  var div =  document.getElementById(id);
  div.style.visibility = 'visible';
  switch (id)
  {
  	case 'commentScrollTrack':
	  div.style.display = 'inline';
	break;
	default:
	  div.style.display = 'block';
	break;
  }
}

function hide_div(id) {
  var div =  document.getElementById(id);
  if (div){
    div.style.visibility = 'hidden';
    div.style.display = 'none';
  }
}
function change_background_color(id, color) {
  var div =  document.getElementById(id);
  if(div){
    div.style.backgroundColor = color;
  }
}

function center_container(){
  var screen_dimensions = {width: 0, height: 0};
  if (document.documentElement) {
    screen_dimensions.width = document.documentElement.offsetWidth;
    screen_dimensions.height = document.documentElement.offsetHeight;
  } else if (window.innerWidth && window.innerHeight) {
    screen_dimensions.width = window.innerWidth;
    screen_dimensions.height = window.innerHeight;
  }
  var left = (screen_dimensions.width/2)-($("#container").width()/2);
  var top = (screen_dimensions.height/2)-250;
  $("#container").css("margin-left", Math.max(0,left));
  $("#container").css("margin-top", Math.max(0,top));
}

// poupulate countries from xml in "country" combo box
$(document).ready(function(){
  $.ajax({
     type:"GET",
     url: get_siteurl() + "/wp-content/themes/conversation_capital/outlets.xml",
     data: "",
     dataType: "xml",
     success: function(xml){
      $("#outlets").html("");
      $(xml).find('country').each(function(){
        var id = $(this).attr("id");                   
        var label = $(this).attr("label");
        var str ='<option value="'+id+'">'+label+'</option>';
        $(str).appendTo($("#country"));
      });
  }});
});

// Load outlets list from xml when "country" combo box change 
$(document).ready(function(){               
  $("#country").change(function(){
    var country = $("#country").val();
    if(country != ""){
      $("#outlets").html('Loading...');
      $.ajax({
           type:"GET",
           url: get_siteurl() + "/wp-content/themes/conversation_capital/outlets.xml",
           data: "",
           dataType: "xml",
           success: function(xml){
            $("#outlets").html("");
            $(xml).find('country').each(function(){
              if($(this).attr("id") == country){
                $(this).children().each(function(){
                  var name = $(this).find('name').text();
                  var picture = $(this).find('picture').text();
                  var url = $(this).find('url').text();
                  var str = '<p style="nospaces"><a href="'+url+'" target="_blank"><img src="' + get_siteurl() + '/wp-content/themes/conversation_capital/images/outlets/'+picture+'" alt="'+name+'" height="50" width="280" /></a></p>';
                  $(str).appendTo($("#outlets"));
                });  
              }                    
            });    
            
        }});
    }
  });
});
function initPostPage() {
  scrObj.scrollContent = "category";
  scrObj.scrollUpImg = get_siteurl() + "/wp-content/themes/conversation_capital/images/scroll/scrollLeft.gif"; //scroll
  scrObj.scrollDownImg = get_siteurl() + "/wp-content/themes/conversation_capital/images/scroll/scrollRight.gif";
  scrObj.scrollerImg = get_siteurl() + "/wp-content/themes/conversation_capital/images/scroll/scrollerBg.gif";    
  scrObj.scrollerBGImg = get_siteurl() + "/wp-content/themes/conversation_capital/images/scroll/scrollerBgImg.gif";
  scrObj.scrollBtnWidth= 18;
  scrObj.scrollBtnHeight= 17;
  scrObj.scrollerFixedWidth=140;
  scrObj.trackHideOnDisabled= true;
  scrObj.direction = 1;

//scrObj.trackHideOnDisabled= 1;
  scrObj.init();
}

function resizer_scroller(){
  winH= (document.body.clientHeight);
  winW= (document.body.clientWidth);
  pTop = Math.round((winH- 500)/2);
 // if (pTop < 70) pTop = 70;
  if (pTop < 40) pTop = 40;
	
  document.getElementById("category").style.width = winW + "px";
  document.getElementById("category").style.height = winH + "px";
  //alert (winW + "," + winH);
  var is_ie = ((navigator.appVersion.match(/\bMSIE\b/))?true:false);
  var is_firefox = /Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)
  postWrapperWidth = ((pageColumns) * 317);
  
  
  if(is_firefox){
  	
  } else if(is_ie) {
	
  } else {
	  
  }
  //document.getElementById("postWrapper").style.backgroundColor = "#FF0000";
   //document.getElementById("category").style.backgroundColor = "#00FF00";
  document.getElementById("postWrapper").style.width = postWrapperWidth + "px";
  //alert(document.getElementById("postWrapper").style.width);
  //document.getElementById("category").style.width = (postWrapperWidth+300) + "px";
  //document.getElementById("postWrapper").style.marginTop = (pTop - 30)+ "px";
  if (typeof(mTop) == 'undefined') {
	  document.getElementById("postWrapper").style.marginTop = pTop + "px";
  }
  else{
	  document.getElementById("postWrapper").style.marginTop = pTop - mTop + "px";
  }
    
  switch(row){
    case 1:
    break;
    case 2:
      scrool_position = winH - 107;
    break;
    case 3:
      scrool_position = winH - 77;
    break;
    case 4:
      scrool_position = winH - 47;
    break;
    case 5:
      scrool_position = winH - 17;
    break;
  }
  //alert((5-row) * 36);
  
  //alert(scrool_position);
  document.getElementById("scrObjTrack").style.top = scrool_position + "px";
  document.getElementById("scrObjTrack").style.width = (winW) + "px";
  if(scrObj.initiated){
    scrObj.refresh();
  }
}

function resize(){
    div_height = document.body.clientHeight-150;
    var div_comment_height = document.body.clientHeight-180;
  
    var div_padding = (div_height/2) - 40;
  if(document.getElementById('content_1') != null){
    document.getElementById('content_1').style.height = Math.max(0, div_height) + 'px';
    document.getElementById('content_1').style.width = document.body.clientWidth + 'px';
  }
  if(document.getElementById('content_2') != null){
    document.getElementById('content_2').style.height = Math.max(0, div_height) + 'px';
  } else {
    setTimeout("document.getElementById('content_2').style.height = div_height + 'px';",1);
  }
  if(document.getElementById('content_3') != null){
    document.getElementById('content_3').style.height = Math.max(0, div_height) + 'px';
  }
  if(document.getElementById('content_4') != null){
    document.getElementById('content_4').style.height = Math.max(0, div_height) + 'px';
  }
  if(document.getElementById('comments') != null){
	//document.getElementById('comments').style.height = div_comment_height + 'px';
   // alert(div_comment_height+" "+document.getElementById('comments').style.height);
	var comment_box_height = Math.max(1, document.body.clientHeight-200) + 'px';
    var read_box_height = Math.max(1, document.body.clientHeight-270) + 'px';
    document.getElementById('comments').style.height = comment_box_height;
    //alert(comment_box_height+" "+document.getElementById('comments').style.height);
    document.getElementById('read').style.height = read_box_height;
    
    document.getElementById("commentScrollTrack").style.height = Math.max(1,document.body.clientHeight-270) + 'px';
    //alert(document.body.clientHeight-286);
	if(document.getElementById("commentScrollTrackInner")) {
		document.getElementById("commentScrollTrackInner").style.height = Math.max(1, document.body.clientHeight-306) + 'px';
   
	}
  }
  if(document.getElementById("tv_flash")) {
    document.getElementById("tv_flash").style.width = document.body.clientWidth;
    if(document.getElementById('CCTVInstance')){
      document.getElementById('CCTVInstance').width = document.body.clientWidth;
      document.getElementById('CCTVInstance').height = document.body.clientHeight - 150;
    } else {
      document.getElementById('CCTVInstance_ie').width = get_div_width();
      document.getElementById('CCTVInstance_ie').height = get_div_height();
    }
  }

  if(document.getElementById('new_post') != null){
      document.getElementById('new_post').style.height = Math.max(0, document.body.clientHeight-200) + 'px';
    }
    
    if(document.getElementById('share') != null){
      document.getElementById('share').style.height = Math.max(0, document.body.clientHeight-200) + 'px';
    }
    
    for (i=1;i<=5;i++) 
    {
      div_loading = document.getElementById('loading_' + i);
      if (div_loading != null){
        div_loading.style.paddingTop = Math.max(0, div_padding) + 'px';
      }
    }
    
    if(document.getElementById("postWrapper") != null){
      setTimeout("resizer_scroller();initPostPage()",200);
    }
    if(document.getElementById("container") != null){
      center_container();
    }
  
  if(document.getElementById("commentScrollTrack")){ 
      if(checkBrowserVersion()){
	//if (!/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent)){
    	setTimeout("commentScroll.refresh();",200);
    }
  }
}
  
function copyToClipboard(s)
{
  if( window.clipboardData && clipboardData.setData )
  {
	clipboardData.setData("Text", s);
  }
  else
  {
	alert('this feature does not work under firefox');
  }
}

function scrollToId(which)
{
  document.getElementById("category").scrollLeft = document.getElementById(which).offsetLeft -30;
  scrObj.refresh();
}

function removeLastWord(string) {
  var words = string.split(" ");
  words.pop();
  words.pop();
  return words.join(" ");
}

function fill_text(div_id, h_max, string, h_max_last_row){
  var id = 0;
  var column_width = 310;
  var totalwidth = column_width;
  var words = string.split(" ");
  var word = "";
  var word_before = "";
  var num_col = 1;
  document.write('<div class="column" id="'+div_id+id+'"></div>');
  while(words.length>1) {
    var cur_div = document.getElementById(div_id+id);
    words.reverse();
    word_before = word;
    word = words.pop();
    words.reverse();

    if(!(
      (  (word.length == 0 )
      || (word.toLowerCase() == "<br/>") 
      || (word.toLowerCase() == "<br>") )
      && (cur_div.innerHTML.length<1))
    ){
       cur_div.innerHTML += word + " ";
    }

    if(cur_div.clientHeight > h_max){
      if(!((word == "<br/>")||(word.length<1)))
      {
        cur_div.innerHTML = removeLastWord(cur_div.innerHTML) + " ";
        for(i=0;i<100;i++)  cur_div.innerHTML += "&nbsp;";
      }
      cur_div.innerHTML = decode_html(cur_div.innerHTML);
      words.reverse();
      word = words.push(word);
      words.reverse();
      cur_div.style.height = h_max+"px";
      id++;
      document.write('<div class="column" id="'+div_id+id+'"></div>');
      totalwidth += column_width;
      num_col++;
    }
  }
  words.reverse();
  word = words.pop();
  words.reverse();
  document.getElementById(div_id+id).innerHTML += word;
  cur_div.innerHTML = decode_html(cur_div.innerHTML);
  if(cur_div.clientHeight > h_max_last_row){
    document.write('<div class="column" id="'+div_id+id+'">&nbsp;</div>');
    num_col++;
  }
  return num_col;
}

function decode_html(string) {
  string = string.replace(/&lt;/g, '<');
  string = string.replace(/&gt;/g, '>');
  return string;
}

function var_dump(obj) {
  if(typeof obj == "object") {
    return "Type: "+typeof(obj)+((obj.constructor) ? "\nConstructor: "+obj.constructor : "")+"\nValue: " + obj;
  } else {
        return "Type: "+typeof(obj)+"\nValue: "+obj;
  }
}//end function var_dump

function checkBrowserVersion()
{
	thisUserAgent = navigator.userAgent;
	//alert (thisUserAgent);
	var thisBrowser;
	if (/Firefox[\/\s](\d+\.\d+)/.test(navigator.userAgent))
	{ 
		//test for Firefox/x.x or Firefox x.x (ignoring remaining digits);
		thisBrowser = 'Firefox';
		
		var ffversion=new Number(RegExp.$1) // capture x.x portion and store as a number
		
		if (ffversion>=3)
		{
			return true;
		}
		else
		{
			return false;
		}
	}
	
	return true;
}


var totalColumns = 0;
function fillParagraph(id, text, width, height)
{
	var last_is_special = false;
	var special_value = null;
	var nb_colum = 1;
	var style = ' style="display: inline-block;"';
	text = unescape(text);
	var t = text.split(' ');
	var paragraph;
	var strToAdd = '';
	var n = 0;
	var h = 0;
	var tmp = '';
	var strlength, restarter, thisSize, multiplicateur, imgH, imgW, breakline;
	
	for(var i=0; i<t.length; i++)
	{
		h=0;
		multiplicateur = 1;
		special_value = null;
		tmp = '';
		paragraph = document.getElementById(id+'_'+n);
		breakline = false;
		while(h <= height)
		{
			if(i >= t.length)
			{
				break;	
			}
			
			strlength = paragraph.innerHTML.length;
			restarter = i -1;
			
			if(t[i].indexOf('{breakline}') >= 0)
			{
				breakline = true;
				break;
			}
			else if(t[i].indexOf('<br>') >= 0 && strlength <= 0)
			{
				t[i] = '';
			}
			else if(t[i].indexOf('<a') >= 0)
			{
				last_is_special = true;
				tmp = t[i];
				while(t[i].indexOf('</a>') < 0)
				{
					i++;
					if(t[i].indexOf('width') >= 0 && tmp.indexOf('<img') >= 0 )
					{
						tImg = t[i].split('=');
						imgW = parseInt(tImg[1].replace('"', ''));
						//alert(tImg[1] > width);
						if(tImg[1] > width)
						{
							multiplicateur = (width / imgW) * 0.9 ;
						}
						else
						{
							multiplicateur = 1;
						}
						//alert(multiplicateur);
					}
					
					if(t[i].indexOf('height') >= 0 && tmp.indexOf('<img') >= 0 )
					{
						tImg = t[i].split('=');
						imgH = parseInt(tImg[1].replace('"', ''));
						//alert(imgH + " x "+ imgW + " " + height);
						
						if( imgH * multiplicateur > height )
						{
							multiplicateur = (height / imgH) * 0.9;
						}
						/*
						else
						{
							multiplicateur = 1;
						}
						*/
						//alert(multiplicateur);
					}
					
					tmp += " " +t[i];
				} 
				if(multiplicateur != 1)
				{
					tmp = tmp.replace(/height=\"([0-9]*)/, 'height="' + Math.round( imgH * multiplicateur ) );
					tmp = tmp.replace(/width=\"([0-9]*)/, 'width="' + Math.round( imgW * multiplicateur ) );
					//alert(tmp);
				}
				special_value = tmp;
				paragraph.innerHTML += tmp + ' ';
			} 
			else if(t[i].indexOf('<object') >= 0) 
			{
				tmp = t[i];
				while(t[i].indexOf('</object>') < 0)
				{
					i++;
					if(t[i].indexOf('width') >= 0 )
					{
						tImg = t[i].split('=');
						imgW = parseInt(tImg[1].replace('"', ''));
						//alert(tImg[1] > width);
						if(tImg[1] > width)
						{
							//alert(tImg[1] +" > " + width)
							multiplicateur = (width / imgW);// * 0.90 ;
						}
						else
						{
							multiplicateur = 1;
						}
						//alert(multiplicateur);
					}
					
					if(t[i].indexOf('height') >= 0 )
					{
						tImg = t[i].split('=');
						imgH = parseInt(tImg[1].replace('"', ''));
						//alert(imgH + " x "+ imgW + " " + height);
						
						if( imgH * multiplicateur > height )
						{
							//alert(tImg[1] +" > " + height)
							multiplicateur = (height / imgH);// * 0.90;
						}
					}
					tmp += " " +t[i];
				} 
				if(multiplicateur != 1)
				{
					tmp = tmp.replace(/height=\"([0-9]*)/g, 'height="' + Math.round( imgH * multiplicateur ) );
					tmp = tmp.replace(/width=\"([0-9]*)/g, 'width="' + Math.round( imgW * multiplicateur ) );
					//alert(tmp);
				}
				paragraph.innerHTML += tmp + ' ';
			} 
			else if(t[i].indexOf('<img') >= 0) 
			{
				last_is_special = true;
				tmp = t[i];
				while(t[i].indexOf('/>') < 0)
				{
					i++;
					if(t[i].indexOf('width') >= 0)
					{
						tImg = t[i].split('=');
						imgW = parseInt(tImg[1].replace('"', ''));
						//alert(tImg[1] > width);
						if(tImg[1] > width)
						{
							multiplicateur = (width / imgW) * 0.9 ;
						}
						else
						{
							multiplicateur = 1;
						}
						//alert(multiplicateur);
					}
					
					if(t[i].indexOf('height') >= 0)
					{
						tImg = t[i].split('=');
						imgH = parseInt(tImg[1].replace('"', ''));
						//alert(imgH + " x "+ imgW + " " + height);
						
						if( imgH * multiplicateur > height )
						{
							multiplicateur = (height / imgH) * 0.9;
						}
					}
					
					tmp += " " +t[i];
				} 
				if(multiplicateur != 1)
				{
					tmp = tmp.replace(/height=\"([0-9]*)/, 'height="' + Math.round( imgH * multiplicateur ) );
					tmp = tmp.replace(/width=\"([0-9]*)/, 'width="' + Math.round( imgW * multiplicateur ) );
					//alert(tmp);
				}
				
				special_value = tmp;
				//alert(tmp);
				paragraph.innerHTML += tmp + ' ';
			} 
			else if(t[i].indexOf('<li>') >= 0) 
			{
				last_is_special = true;
				tmp = t[i];
				while(t[i].indexOf('</li>') < 0)
				{
					i++;
					tmp += " " + t[i];
				} 
				special_value = tmp;
				paragraph.innerHTML += tmp + ' ';
			} 
			else 
			{
				paragraph.innerHTML += t[i] + ' ';
			}
			
			h = paragraph.clientHeight;
			i++;
		}
		//alert(i + " / "+ t.length + " / "+ restarter + " / "+ h  + " / "+ height);
		newInner = paragraph.innerHTML.substr(0, strlength-1);
		
		if( (i <= t.length && h > height) || (breakline == true) )
		{
			if(breakline == true)
			{
				t[i] = '';
			}
			document.write('<div class="col2"><div id="' + id + '_' + (n+1) + '" class="author_desc" ' + style +'></div></div>\n');
			i = restarter;
			n++;
			nb_colum++;
			newInner = paragraph.innerHTML.substr(0, strlength-1);
			
		}
		else
		{
			newInner = paragraph.innerHTML;
			paragraph.innerHTML = newInner;
			//alert(i + " / "+ t.length + " / "+ restarter + " / "+ h  + " / "+ height);
			break;
		}
		paragraph.innerHTML = newInner;
	}

	document.getElementById(id).style.width = (nb_colum * 310 - 30) + "px";
	totalColumns += nb_colum; 
	//alert(totalColumns);
}