$(document).ready(function(){

adjust();

$(window).resize(function(){
  adjust()
});
// ---
$('.search').live(
  "keyup",function(event) {
    var sort = $(this).attr('data-sort');
    if(sort!=undefined) s=sort;
    else s='0';
  var divs = $(this).attr("data-div");
    var vars = $(this).attr("data-vars");
    divs = divs.split(",");
    infield=divs[0];
    sfield=divs[1];
    q=this.value;
    switch(event.keyCode) {
    case 27:  // to clear everything
      document.getElementById(infield).value='';
      document.getElementById(infield).focus;
      document.getElementById(sfield).innerHTML='';
    break;
    default:
      ph2=parseInt(divs[2])+100;
      if(q.length>=divs[2] && q.length<ph2) {
        $.ajax({
          type: "post",
          url: "core/ajax.php",
          data: {ajax: "ajax", vars: vars, sort : s, term: q}, 
	        beforeSend: function(){
          $("#loading").show("fast");},
		      complete: function(){ $("#loading").hide("fast");},
		      success: function(html){
          $("#"+sfield).html(html);
          //$("#"+infield).focus();
          }
		    });
      }
    break;
    } 

});

// ---

$('.auto').live(
  "keyup",function() {
  var vars = $(this).attr("data-vars");
  var par = $(this).attr("data-par");
      par = par.split(",");
	var mL = par[0];
	var It1=par[1];
	var It2=par[2];
	var It3=par[3];
	var It4=par[4];
	
	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	
	$(this).autocomplete({
    minLength: mL,
		source: function(request, response) {
		  $.ajax({url: "core/ajax.php",dataType: "json",data: {ajax: "ajax", vars: vars, term:extractLast(request.term)},success: function(data) {
        response($.map(data, function(item) {return {f1: item.f1,f2: item.f2, f3:item.f3, f4:item.f4, value: item.value}}))},
        type:"POST",})},
			focus: function(event, ui) {$('#'+It1).val(ui.item.f2);return false;},
			select: function(event, ui) {
				if(It1!='') $('#'+It1).val(ui.item.f1);
				if(It2!='') $('#'+It2).val(ui.item.f2);
				if(It3!='') $('#'+It3).val(ui.item.f3);
				if(It4!='') $('#'+It4).val(ui.item.f4);
				
				return false;
        //$('ul.ui-autocomplete').remove();
        }
      })
		.data( "autocomplete" )._renderItem = function( ul, item ) {return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append("<a>"+item.value+"</a>" )
				.appendTo( ul );};

});

// ---

$('.auto2').live(
  "mouseover",function() {
  var vars = $(this).attr("data-vars");
  var par = $(this).attr("data-par");
      par = par.split(",");
	var mL = par[0];
	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	$(this).autocomplete({
    minLength: mL,
		source: function(request, response) {
		  $.ajax({url: "core/ajax.php",dataType: "json",data: {ajax: "ajax", vars: vars, term:extractLast(request.term)},success: function(data) {
        response($.map(data, function(item) {return {f1: item.f1, f2: item.f2, value: item.value}}))},
        type:"POST",})},
			focus: function() {
				// prevent value inserted on focus
				return false;
			},
			select: function(event, ui) {
				var terms = split( this.value );
				//if(It1!=undefined) {
        //  var value2=$('#'+It1).val();
        //  var terms2= split(value2);
        //  terms2.pop();
        //  terms2.push( ui.item.f2 );
        //  terms2.push("");
        //  value2=terms2.join(",");
        //  $('#'+It1).val(value2);
        //}
 				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
      })
		.data( "autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append("<a>" + item.f1 + "</a>")
				.appendTo( ul );};

});

// ---

$('.sendTo').live(
  "mouseover",function() {
  var vars = $(this).attr("data-vars");
  var par = $(this).attr("data-par");
      par = par.split(",");
	var mL = par[0];
	var It1=par[1];
	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}
	$(this).autocomplete({
    minLength: mL,
		source: function(request, response) {
		  $.ajax({url: "core/ajax.php",dataType: "json",data: {ajax: "ajax", vars: vars, term:extractLast(request.term)},success: function(data) {
        response($.map(data, function(item) {return {f1: item.f1, f2: item.f2, value: item.value}}))},
        type:"POST",})},
			focus: function() {
				// prevent value inserted on focus
				return false;
			},
			select: function(event, ui) {
				var terms = split( this.value );
				if(It1!=undefined) {
          var value2=$('#'+It1).val();
          var terms2= split(value2);
          terms2.pop();
          terms2.push( ui.item.f2 );
          terms2.push("");
          value2=terms2.join(",");
          $('#'+It1).val(value2);
        }
 				// remove the current input
				terms.pop();
				// add the selected item
				terms.push( ui.item.value );
				// add placeholder to get the comma-and-space at the end
				terms.push("");
				this.value = terms.join(", ");
				return false;
			}
      })
		.data( "autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li></li>" )
				.data( "item.autocomplete", item )
				.append("<a>" + item.f1 + "</a>")
				.appendTo( ul );};

});


// ---

  $('.sh').live(
    "click",function() {
    var vars = $(this).attr("data-vars");
    vars = vars.split(",");
    var w_id=vars[0];
    var s_id=vars[1];
    var w_name=vars[2];
    if ($('#'+w_id).is(":hidden")) {
      $('#'+w_id).slideDown("slow");
      $('#'+s_id).removeClass('button').addClass('button_p');
    } else {
      $('#'+w_id).slideUp("slow");
      $('#'+s_id).removeClass('button_p').addClass('button');
    }
  });

// ---

// $('.shAlert').live(
//  "click",function() {
//    var vars = $(this).attr('data-vars');
		//$('.sh_alert').html(vars);
   // $('.sh_alert').fadeIn("fast");
  //  $('.sh_alert').delay(2000).fadeOut("fast");
    
//  });
  
// ---

function enterc(evt,f) {
  var charCode=(evt.which)?evt.which:window.event.keyCode;
  if (charCode == 13) {
    var shoutc=f.shoutc.value;
    updatecompetition(shoutc);
    document.getElementById("shoutc").value=('');
    document.getElementById("shoutc").focus();
  }
}

$('.shoutarea').keypress(function(event) {
  if (event.keyCode == '13') {
    var divs = $('[name=fshout]').attr("data-div");
    var vars = $('[name=fshout]').attr("data-vars");
    
    var  fcontent = $('[name=fshout]').serialize();
    
    divs = divs.split(",");
    vars = vars.split(",");
  
    var m_bg = divs[0];
    var m_id = divs[1];
    var e_focus = divs[2];
    $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: "ajax=ajax&vars="+vars+"&"+fcontent,
		//beforeSend: function(){
      //$("#loading").show("fast");},
		//complete: function(){ $("#loading").hide("fast");},
		success: function(html){
		  $("#"+m_id).html(html);
      $("#"+m_id).show("fast");
      document.getElementById('shout').value='';
      $("."+e_focus).focus();
    }
	});
  }
});

// ----

$('.shoutareac').live(
  "keypress",function(event) {
  if (event.keyCode == '13') {
    var divs = $('[name=fshoutC]').attr("data-div");
    var vars = $('[name=fshoutC]').attr("data-vars");
    var  fcontent = $('[name=fshoutC]').serialize();
    divs = divs.split(",");
    vars = vars.split(",");
    
    if(divs!=undefined) {
      getFocus=divs[0];
      closeButton=divs[1];
      bgClass=divs[2];
      mainWin=divs[3];
      newClass=divs[4];
    }
    else divs='0';
    
  
    
    $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: "ajax=ajax&vars="+vars+"&"+fcontent,
		beforeSend: function(){
      $("#loading").show("fast");},
		complete: function(){ $("#loading").hide("fast");},
		success: function(html){
      $("#"+mainWin).html(html);
      document.getElementById('shoutC').value='';
      $("."+getFocus).focus();
    }
	});
  }
});

// ----


// ----

  $('.help').live(
  "click",function() {
    var vars=$(this).attr('data-vars');
    var window_width = $(window).width();  
    var window_height = $(window).height();
    var max_height=window_height-100;
    
    $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: {ajax: "ajax", vars: vars},
	  beforeSend: function(){
      $("#loading").show("fast");},
		complete: function(){ $("#loading").hide("fast");},
		success: function(html){
      $('.h_w').html(html);
      $('.h_w').css({'max-height' : max_height});
      $('.h_w').slideDown();
    }
		});
  });

// ----

$('#plus').live(
  "click",function() {
    var currentFS=$('.default').css('font-size');
    var currentFSN=parseFloat(currentFS, 10);
    var newFS=currentFSN*1.5;
    $(".default").css({'font-size' : newFS});
    center_modal("0","m_w1");
  });

$('#minus').live(
  "click",function() {
    var currentFS=$('.default').css('font-size');
    var currentFSN=parseFloat(currentFS, 10);
    var newFS=currentFSN*0.5;
    $(".default").css({'font-size' : newFS});
  });


// ----

$('.top_but').click(function() {
  var vars=$(this).attr('data-vars');
  var window_width = $(window).width();  
  var window_height = $(window).height();
  var max_height=window_height-100;
  var left=150;
  var right=250; 
  $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: {ajax: "ajax", vars: vars},
	  beforeSend: function(){
      $("#loading").show("fast");},
		complete: function(){ $("#loading").hide("fast");},
		success: function(html){
		  $("#m_w2").html(html);
      $('.m_w2').css({'max-height' : max_height});
      $('#m_w2').slideDown();
    }
		});
});

$('.win_close').live(
  "click",function() {
  $(this).parent().slideUp();
});

$('.top_close').live(
  "click",function() {
  $("#m_w2").slideUp();
});
  
});  
  
// --- functions  

function s(div,vars) {
  $.post("core/ajax.php",{ajax:"ajax",vars: vars},function(html) {
      $("#"+div).html(html).fadeIn(2000).fadeOut(5000);},"html")
}; 

// ----


function adjust() {
  var window_width = $(window).width();
  var window_height = $(window).height();
  if(window_width<1024) window_width=1024;
  var shoutboxh=window_height-200;
  var showShoutboxh=window_height-255;
  var logoutw=window_width-145;
  var content_width=window_width-400;
  var shoutboxw=content_width+165;
  var m_w2_width=content_width-140;
  var contenth=window_height-155;
  //$('.content').css({ 'width': content_width+'px', 'min-height': contenth+'px'});
  $('.content').css({ 'width': content_width+'px'});
  $('.content_b').css({ 'width': content_width+'px'});
  $('.m_w2').css({ 'width': m_w2_width+'px'});
  $('.extra').css({ 'width': content_width+'px'});
  $('.shoutbox').css({ 'left': shoutboxw+'px'});
  $('.shoutbox').css({ 'height': shoutboxh+'px'});
  $('.shoutbox_top').css({ 'left': shoutboxw+'px'});
  $('#showShoutbox').css({ 'height': showShoutboxh+'px'});;
}
 
// ---

function adjust_window(w) {
  var window_width = $(window).width();  
  var window_height = $(window).height();
  window_height=window_height-100;
  $('.'+w).css({ 'height': window_height+'px'});
}
 
// ---


// ----

function getGap(tfield,field,field2) {
  var selectedText;
  var text=document.getElementById(tfield).innerHTML;
  if(window.getSelection) selectedText=window.getSelection();
  else if(document.selection) selectedText=document.selection.createRange();
  if(selectedText!='') {
    var range=selectedText.getRangeAt(0);
    var length=(range.startOffset);
    var position=(range.startOffset)-1;
    if(position==-1) position=0;
    
    var count = 0;
    var idx = 0;
    var count2='';
    var count3='';
     while ((idx = text.indexOf(selectedText, idx)) != -1)
     {
        idx++;
        count++;
        idx2=idx-1;
        if(idx2==length) count3=count;
     }
    selectedText=selectedText.toString();
    selectedText=selectedText.replace(/^\s+|\s+$/g,"");
    if(count>1) {
      part1=text.substring(0,position);
      part2=text.substring(position);
      part2=part2.replace(selectedText,"["+selectedText+"]");
      textToPut=part1+part2;
    }
    else textToPut=text.replace(selectedText,"["+selectedText+"]");
    document.getElementById(tfield).innerHTML=textToPut;
    document.getElementById(field).value=selectedText;
    document.getElementById(field2).value=count3;
  }
}

function gapReset(tfield,field,field2) {
  var selectedText;
  var text=document.getElementById(tfield).innerHTML;
  text1=text.replace("[","");
  textToPut=text1.replace("]","");
  document.getElementById(tfield).innerHTML=textToPut;
  document.getElementById(field).value='';
  document.getElementById(field2).value='';
}

function checkLength(str,limit,infield) {
  str=str.length;
  if(str==limit) document.getElementById(infield).focus();
}

function showNext(elem) {
  elem=document.getElementById(elem);
  elem.setAttribute('style','display:table-row;');

}

function options(nb) {
  if(nb<=10) {
    var div = document.getElementById('options');
    var v=nb+30;
    nb++;
    var label = document.createElement('label');
    label.innerHTML="option: ";
    var input = document.createElement('input');
    input.setAttribute('type','text');
    input.id='v'+v;
    input.name='v'+v;
    input.className='t400';
    input.setAttribute('onfocus','options('+nb+');');
    var input2 = document.createElement('input');
    input2.setAttribute('type','checkbox');
    input2.id='c'+v;
    input2.name='c'+v;
    input2.setAttribute('value','1');
    var br = document.createElement('br');
    div.appendChild(label);
    div.appendChild(input);
    div.appendChild(input2);
    div.appendChild(br);
  }
}

function mc(id,v,id2) {
  v=v.replace("#","'");
  document.getElementById(id).value=v;
  var e=document.getElementsByName('s'+id);
  for(var i=0;i<e.length;i++){e[i].style.backgroundColor=''}
  document.getElementById(id2).style.backgroundColor='#c0c0c0';
}

function GetXmlHttpObject() {
 var xmlHttp=null;
 
 try {
  // Firefox, Opera 8.0+, Safari
  xmlHttp=new XMLHttpRequest();
 }
 catch (e) {
  // Internet Explorer
  try {
   xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
  }
  catch (e) {
   xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 }
 return xmlHttp;
}

function statusCheck() {
$.ajax({
    type: "post",
    url: "core/statuscheck.php?sid="+Math.random(),
    success: function(html){
		  statusUpdate(html);
		  $("#statuscheck").html('');
		  $("#random").html(Math.random());
      $("#statuscheck").html(html);
    }
		});
}

function statusUpdate(response) {
  cL=response.substring(0,10);
  cO=response.substring(10,20);
  cS=response.substring(20,30);
  cA=response.substring(30,40);
  cU=response.substring(40,50);
  cM=response.substring(50,60);
  cV=response.substring(60,70);
  cN=response.substring(70,80);
  cA2=response.substring(80,90);
  pL=document.getElementById("stL").value;
  pO=document.getElementById("stO").value;
  pS=document.getElementById("stS").value;
  pA=document.getElementById("stA").value;
  pU=document.getElementById("stU").value;
  pM=document.getElementById("stM").value;
  pV=document.getElementById("stV").value;
  pN=document.getElementById("stN").value;
  pA2=document.getElementById("stA2").value;
  if(pL!=cL) {
    showContent('2148','showLogin');
    document.getElementById("stL").value=cL;
  }
  if(pO!=cO) {
    showContent('2147','showOnline');
    document.getElementById("stO").value=cO;
  }
  if(pS!=cS) {
    showContent('2117','showShoutbox');
    document.getElementById("stS").value=cS;
  }
  if(pA!=cA) {
    showContent('2115','showActivity');
    document.getElementById("stA").value=cA;
  }
  if(pU!=cU) {
    showContent('2114','showUpdate');
    document.getElementById("stU").value=cU;
  }
  if(pM!=cM) {
    showContent('2113','showMessage');
    document.getElementById("stM").value=cM;
  }
  if(pV!=cV) {
    showContent('2112','showV');
    document.getElementById("stV").value=cV;
  }
  if(pN!=cN) {
    showContent('2111','showN');
    document.getElementById("stN").value=cN;
  }
  if(pA2!=cA2) {
    showContent('2110','showA2');
    document.getElementById("stA2").value=cA2;
  }
}

function showContent(vars,m_id) {
  $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: "ajax=ajax&vars="+vars,
		success: function(html){
		  if(m_id=='showLogin') $("#"+m_id).html(html).fadeIn('3000').delay('5000').fadeOut('3000');
		  //else if(m_id=='showV') $("#"+m_id).html(html).fadeIn('3000');
		  //else $("#"+m_id).html(html);
		  else $("#"+m_id).html(html).fadeIn('3000');
    }
	});
}

// ----

function cnt(w,x){
  var y=w.value;
  var r = 0;
  a=y.replace('\n',' ');
  a=a.split(' ');
  for (z=0; z<a.length; z++) {
    if (a[z].length > 0) r++;
  }
  x.value=r;
}

function showRevision(i,rmax,variant,variant2,speed) {
  //alert("i:"+i+" rmax:"+rmax);
  document.getElementById("revbuttons").style.display='none';
  document.getElementById("show2").innerHTML='';
  if(rmax==0) {
    div=document.getElementById("data2");
    li=div.getElementsByTagName("li");
    rmax=li.length;
  }
  if(i==rmax) {
    $("#bg").fadeOut(500).removeClass();
    $("#mw1").fadeOut(500).html('').removeClass();  
  }
  else {
    document.getElementById("show1").innerHTML=document.getElementById("s"+variant+i).innerHTML;
    setTimeout("showRevision2('"+i+"','"+rmax+"','"+variant2+"','"+variant+"','"+speed+"')",speed);
  }
}

function showRevision2(i,rmax,variant,variant2,speed) {
  document.getElementById("show2").innerHTML=document.getElementById("s"+variant+i).innerHTML;
  i++;
  setTimeout("showRevision('"+i+"','"+rmax+"','"+variant2+"','"+variant+"','"+speed+"')",speed);
}

// JavaScript Document
function setupExtDoubleClick(A,E,D,B,C){setupDoubleClick(A,E,D,B,C,function(F,H,G){return F+"search/"+(H?H+"/":"")+"?q="+G;
});}function setupDoubleClick(C,H,I,E,F,G){if(!C||!H){alert("Please specify required parameters (websiteUrl and dictionary) to setupDoubleClick()");
return ;}var B=function(L){L.preventDefault();var K=getSelectedText();K=K.replace(/[\.\*\?;!()\+,\[:\]<>^_`\[\]{}~\\\/\"\'=]/g," ");
K=K.replace(/\s+/g," ");if(K!=null&&K.replace("/s/g","").length>0){if(E&&K.split(/[ -]/).length>E){return ;
}if($("#definition_layer").length==0){var J="http://www.oxfordadvancedlearnersdictionary.com/external/images/doubleclick/definition-layer.gif";$("body").append("<div id='definition_layer' style='position:absolute; cursor:pointer;'><img src='"+J+"' alt='' title=''/></div>");
}$("#definition_layer").map(function(){$(this).css({left:L.pageX-30,top:L.pageY-40});});$("#definition_layer").mouseup(function(M){M.stopPropagation();
D(K);});}else{$("#definition_layer").remove();}};var D=function(L){var K;if(G){K=G(C,H,L);}else{K=C+"search/"+(H?H+"/":"")+"?q="+L;
}if(F){var J=window.open(K,F,"toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=no,copyhistory=no,width=800,height=550,top=200,left=200");
if(J){J.focus();}}else{window.open(K,"cup_lookup");}};var A=I?"#"+I:"body";$(A).mouseup(B);}function getSelectedText(){if(window.getSelection){return window.getSelection().toString();
}else{if(document.getSelection){return document.getSelection();}else{if(document.selection){return document.selection.createRange().text;
}}}return"";}   // {var J=C+

// ----

var compId;

function startCompetition() {  
  compId=setInterval("showCompetition()",3000);
}
function stopCompetition() {  
  clearInterval(compId); 
}
  
function showCompetition() {
  $.ajax({
    type: "post",
    url: "core/ajax.php",
    data: "ajax=ajax&vars=2210",
		success: function(html){
		  $("#showPoints").html(html);
      $("#showPoints").show("fast");
    }
	});
	$.ajax({
    type: "post",
    url: "core/ajax.php",
    data: "ajax=ajax&vars=2211",
		success: function(html){
		  $("#showCompetition").html(html);
      $("#showCompetition").show("fast");
    }
	});
}

var c=0;
var t;
var timer_is_on=0;

function timedCount() {
  document.getElementById('txt').value=c;
  c=c+1;
  if(c<60) c1='0:'+c;
  else if(c==60) c1='1:0';
  else if(c>60 && c<120) c1='1:'+(c-60);
  else if(c==120) c1='2:0';
  else if(c>120 && c<180) c1='2:'+(c-120);
  else if(c==180) c1='3:0';
  else if(c>180 && c<240) c1='3:'+(c-180);
  else if(c==240) c1='4:0';
  else if(c>240 && c<320) c1='4:'+(c-240);
  else if(c==320) c1='5:0';
  else if(c>320 && c<380) c1='5:'+(c-320);
  else if(c>380) stopCount();
  document.getElementById('txt2').innerHTML=c1;
  t=setTimeout("timedCount()",1000);
}

function doTimer() {
  if (!timer_is_on) {
    timer_is_on=1; 
    timedCount();
  }
}

function stopCount() {
  clearTimeout(t);
  timer_is_on=0;
  c=0;
  document.getElementById('txt2').innerHTML='';
}

var showtimer=0;

function CountDownToCompetition() {
  startNext=document.getElementById('startNext').value;
  currentTime=document.getElementById('currentTime').value;
  diff=startNext-currentTime;
  document.getElementById('diff').value=diff-1;
  //alert(diff);
  hours=Math.floor(diff/(60*60));
  minutes=Math.floor(diff/60);
  if(hours>0) minutes2=minutes-(hours*60);
  else minutes2=minutes;
  seconds=diff-(minutes*60);
  if(minutes2<10) zeroM="0";
  else zeroM='';
  if(seconds<10) zeroS="0";
  else zeroS='';
  document.getElementById('showStart').innerHTML=hours+':'+zeroM+minutes2+':'+zeroS+seconds;
  setInterval("showCountDown()",1000);
}

function showCountDown() {
  diff=document.getElementById('diff').value;
  hours=Math.floor(diff/(60*60));
  minutes=Math.floor(diff/60);
  if(hours>0) minutes2=minutes-(hours*60);
  else minutes2=minutes;
  seconds=diff-(minutes*60);
  if(minutes2<10) zeroM="0";
  else zeroM='';
  if(seconds<10) zeroS="0";
  else zeroS='';
  document.getElementById('showStart').innerHTML=hours+':'+zeroM+minutes2+':'+zeroS+seconds;
  document.getElementById('diff').value=diff-1;
  if(diff<=1) window.location.reload();
}

function addDiv(id,divId) {
  alert(divId);
  divTag = document.createElement("div");
  divTag.className ="divId";
  document.getElementById(id).appendChild(divTag);
}
