/*
  FCBKcomplete 1.05
  - Jquery version required: 1.2.x
  
  Changelog:
  - 1.05 bindEvents function fixed thanks to idgnarn
  
  - 1.04 IE7 <em> tag replace fixed
  		 
  - 1.03 IE7 & IE6 crash fixed
  		 IE7 css fixed
  
  - 1.02 json parsing fixed
         remove element fixed
         
  - 1.01: some bugs fixed
  
  - 1.0: migration from prototype
*/

/* Coded by: emposha <admin@emposha.com> */
/* Copyright: Emposha.com <http://www.emposha.com/> - Distributed under MIT - Keep this message! */
/*
* elem - input element id or object
* list - preadded elements
* complete - autocomplete div id or object
* ajax - url to fetch json object
* height - maximum number of element shown before scroll will apear
*/
//	alert (inp);
//	alert (arrFormat);
var timerClearCoures = false;
function w_getCourseFixedValue(inp, arrFormat)
{
	return inp;
	inp = inp.toUpperCase();
	for (var i=0; i<arrFormat.length; i++)
	{
		 var fixedValue = w_getCourseFixed(inp, arrFormat[i]);
	     if (fixedValue)
		     return  fixedValue;
	}
	return false;	   
}; 

function w_isInt(x) {
   var y=parseInt(x);
   if (isNaN(y)) return false;
   return x==y && x.toString()==y.toString();
}; 
function w_isChar(c)
{
 var regExp = new RegExp (/[A-Za-z]/);
 return regExp.test(c);
}; 

function w_getCourseFixed(inp, courseF)
{
		var res = true;
		for (var i=0; i<courseF.length; i++)
		{  
		  var m = courseF[i];
		  for (var j=0; j<inp.length; j++)
		  {
			  alert (j);
			  var m2 = inp[j];
			  alert(m);
			  alert(m2);
			  if (m == 'A')
			  {
				 alert(1);
				 if(!w_isChar(m2))
					return false;
				 else
					continue;
			  }
			  else if (m == '1')
			  {
				 alert(2);
				 if(!w_isInt(m2))
					return false;
				 else
					continue;
			  }
			  else if (m == '^')
			  {
				   alert (3);
			  }
			  
		  }
		  var lastJ = j;
		  continue;
		}  
};

/*******************************************/


var newcoursevalue;
jQuery.facebooklist = function(elem, list, complete, ajax, height, feedid) {
	
	
	var addHiddenInput = function(value) {
	var input = document.createElement('input');    
        $(input).attr({'type': 'hidden', 'name': (elem.attr('id')+'[]'), 'id': (elem.attr('id')+'[]'), 'value': value});
        return input;
    }
    var getChar = function(e) {
    	if(window.event) {
			keynum = e.keyCode;
		} else if(e.which) {
		  keynum = e.which;
    	}
    	if (keynum == 8)
    		return '';
    		
    	return String.fromCharCode(keynum);
    }
	
    var addItem = function(item, preadded) {
    	//@htsoftwares hack take only the username, without the name	
		
	  
        
		var title = item.html().replace(/<em>/gi,'').replace(/<\/em>/gi,'');
    	var titlearray = title.split(" -");
    	title = titlearray[0];
    	
    	var value = (item.attr('val') && item.attr('val') != -1 ?item.attr('val'):title);    	
        var li = document.createElement('li');
        var txt = document.createTextNode(title);
        var aclose = document.createElement('a');
		
		if (value == 'Add this course')
		{
		    value = document.getElementById('add_new_course_input').value;
		    newcoursevalue = value;
		}
		
		var input = addHiddenInput(value);
	    $(li).attr({'val': value, 'class': 'bit-box'});
        $(li).prepend(txt);
        $(aclose).attr({'class': 'closebutton','href': '#'});
        li.appendChild(aclose);
        li.appendChild(input);
		
		
	     
        holder.appendChild(li);        
        $(aclose).click(function() {
            $(this).parent('li').fadeOut('fast',function() {
                $(this).remove();
            });
            return false;
        });
        if (!preadded) {        
        	holder.removeChild(document.getElementById('annoninput'+feedid));
        	addInput();
        }
        $('.default').show();                     
        feed.hide();
		
		/*var holderHTML = document.getElementById('holder').getElementsByTagName('LI');
		for (var i=0;  i< holderHTML.length; i++)
		{
		   //alert (holderHTML[i].innerHTML);
		   holderHTML[i].innerHTML = holderHTML[i].innerHTML.replace('Add this course' , newcoursevalue);
		}*/
        
        //@htsoftwares add callback here to resize
        if(typeof callbackadditem == 'function') {
          callbackadditem();
        }
    }
    var addItemFeed = function(data,input) {
      
      //htsoftwares hack
      //if(data.length == 0)
      //{      
      //  feed.hide();
      //}      
    	feed.children('li[fckb=2]').remove();
    	$.each(data, function(i, val) {
           if (val.caption) {
		    	var li = document.createElement('li');		    	
		        $(li).attr({'val': val.value,'fckb': '2'});
		        $(li).html(val.caption.replace(input,'<em>'+input+'</em>'));
		        feed.append(li);
	    	}           
        });    	
    }
    var addTextItemFeed = function(value) {
    		feed.children('li[fckb=1]').remove();
	    	var li = document.createElement('li');	        
	        $(li).attr({'val':value,'fckb': '1'});
	        $(li).html(value);	        
	        feed.prepend(li);
    }
    //thanks to idgnarn for fix
		//htsoftwares fix put this global
    var nowFocusOn;
    var bindEvents = function () {
     	feed.children('li').mouseover(
     		function(){
                $(this).addClass("auto-focus");
				nowFocusOn=$(this);
            }
        ); 
        feed.children('li').mouseout(
        	function(){
                $(this).removeClass("auto-focus");
				nowFocusOn=null;
        	}
       	);        
        feed.children('li').unbind('click');
        feed.children('li').click(function(){
		   
		var format =  document.getElementById('university').options[document.getElementById('university').selectedIndex].getAttribute ('format');
	    var error =  document.getElementById('university').options[document.getElementById('university').selectedIndex].getAttribute ('error');
		var arrFormat = eval (format);
		var uservalue = document.getElementById('add_new_course_input').value;
		var courseValue = w_getCourseFixedValue( uservalue ,arrFormat); 

		this.innerHTML = this.innerHTML.replace('Add this course' , courseValue );
		if (!this.innerHTML)return;
		
		
			addItem($(this));
            complete.hide();
        });
		$('.maininput').unbind('keypress');
		$('.maininput').keypress(
			function(event){
				if (event.keyCode == 13 && nowFocusOn != null) {
					addItem($(nowFocusOn));
					complete.hide();
					event.preventDefault();
				}
			}
		);
		 
		 
    }
    
    var addInput = function () {
    
	    var li = document.createElement('li');
        var input = document.createElement('input');
		
		
		input.setAttribute ('id' , 'add_new_course_input');
		
		input.setAttribute("onMouseUp", "handleNewCourse()" );
		input.setAttribute("onMouseDown", "handleNewCourse()" );
		input.onclick= function (){handleNewCourse(input)};
		input.onmouseup= function (){handleNewCourse(input)};
		input.onkeydown= function (){handleNewCourse(input)};
		input.onkeypress = function (){ complete.fadeIn('fast')};
		
		
        $(li).attr({'class': 'bit-input', 'id': 'annoninput'+feedid});    
        
        li.appendChild(input);
        holder.appendChild(li);
		
		$(li).click(function() {	 
            complete.fadeIn('fast');
        });
		
        //htsoftwares fix    
        $(input).blur(
          function()
          {
            if(nowFocusOn == null)
            {                                     
             feed.empty(); 
             feed.hide();
             }
          }
        );      
      
	    $(li).keyup(function(event) {
	    	var etext = $(input).val();
	    	//@htsoftwares don't show the text that is inputed as an option as it may not be valid 
	    	//addTextItemFeed(etext);
	        if (ajax) {	            
  	            $.getJSON( ajax+'?university='+document.getElementById('university').value+'&tag='+etext, null,  function(data) {
  	                addItemFeed(data, etext);
  	                bindEvents();
  	            });	            
	        }
	        bindEvents();            
            $('.default').hide();                     
            feed.show();            
			
	  });
		
		
    }    
    if (typeof(elem) != 'object') elem = $(elem);
    if (typeof(list) != 'object') list = $(list);
    if (typeof(complete) != 'object') complete = $(complete);    
    var feed = $(feedid);
    feed.css({'height':(height*24)+'px', 'overflow':'auto'});
	
	
    var holder = document.createElement('ul');
   
	elem.css('display','none');
    $(holder).attr('class', 'holder'); 
	$(holder).attr('id', 'holder'); 
	
	
	if (list && list.children('li').length) {        
        $.each(list.children('li'), function(i, val) {
        	addItem($(list.children('li')[i]),1);           
        });
    }
	
	
	if (document.getElementById('feed-courses'))
	{
		var li = document.createElement('li');	
		li.setAttribute( 'id' , 'add_new_course_li' );
		document.getElementById('feed-courses').appendChild(li);		
    }
	
	
    addInput();
    elem.before(holder);
	
	handleNewCourse = function(e)
	{
		
		if (document.getElementById('feed-courses'))
		{ 
			 //try {document.getElementById('fakeFocusIE').focus()}catch(e){};
			 if (document.getElementById('add_new_course_li'))
				 document.getElementById('add_new_course_li').innerHTML = 'Add this course';
			 else
			 {
	
					document.getElementById('feed-courses').style.display = 'block';
					var li = document.createElement('li');	
					li.setAttribute( 'id' , 'add_new_course_li' );
					li.innerHTML = 'Add this course';
					document.getElementById('feed-courses').appendChild(li);	
			 }
		}
		
		  setInterval ('runTimerClearCoures()' , 100);
	};

	
}

function runTimerClearCoures ()
{
    if (!timerClearCoures)
	       timerClearCoures = setInterval ('timerClearCouresFct()' , 3000);
}
//document.title = timerClearCoures;

function timerClearCouresFct  ()
	{ 
	    //clearInterval (timerClearCouresFct);
	    if (document.getElementById('feed-courses').style.display !='block' && document.getElementById('add_new_course_input'))
		{
               if (document.getElementById('add_new_course_input').value)
			       document.getElementById('add_new_course_input').value = '';
				   
			  
		}
	};

