$.browser.chrome = typeof navigator.vendor != 'undefined' && navigator.vendor.indexOf('Google') != -1;
if (typeof navigator.userAgent != 'undefined') {
    $.browser.iPad = navigator.userAgent.indexOf('iPad') != -1;
    $.browser.iPhone = navigator.userAgent.indexOf('iPhone') != -1;
    $.browser.iPod = navigator.userAgent.indexOf('iPod') != -1;
    $.browser.BlackBerry = navigator.userAgent.indexOf('BlackBerry') != -1;
    $.browser.MobileSafari = navigator.userAgent.indexOf('Mobile Safari') != -1;
    $.browser.HTC = navigator.userAgent.indexOf('HTC') != -1;
    $.browser.LG = navigator.userAgent.indexOf('LG') != -1;
    $.browser.Nokia = navigator.userAgent.indexOf('Nokia') != -1;
    $.browser.SymbianOS = navigator.userAgent.indexOf('SymbianOS') != -1;
    $.browser.Samsung = navigator.userAgent.indexOf('SAMSUNG') != -1;
    $.browser.SonyEricsson = navigator.userAgent.indexOf('SonyEricsson') != -1;

    $.browser.mobile = $.browser.iPad || $.browser.iPhone || $.browser.iPod || $.browser.BlackBerry || $.browser.MobileSafari || $.browser.HTC || $.browser.LG || $.browser.Nokia || $.browser.SymbianOS || $.browser.Samsung || $.browser.SonyEricsson;

	$.browser.msie = navigator.userAgent.indexOf('MSIE') != -1;
}

setTimeout(function(){
	if (typeof console == 'undefined' || typeof console.log == 'undefined') {
	  if (typeof console == 'undefined') {
		  console = {};
	  }
	  if (document.location.host == 'cghub.localhost') {
		console.log = function(obj){
			//alert(myObj.toSource());
			if (typeof obj == 'object') {

				var emptyArray = new Array();
				var log = function(obj) {
					var ret = [];
					for (var key in obj){
						if (typeof obj[key] == 'object') {
							ret.push("'"+key+"': "+log(obj[key]));
						} else if (typeof emptyArray[key] == 'undefined') {
							ret.push("'"+key+"': "+obj[key]);
						}
					}
					return '{'+ret.join("\n")+'}';
				};

				alert(log(obj));
			} else {
				alert(obj);
			}
		};
	  } else {
		console.log = function(){};
	  }
	}
}, 1000);

function getTopDomain() {
	var httpHost = document.location.hostname;
	httpHost = httpHost.split('.');
	
	var level = httpHost.length;
	var isUserDomain;
	
	if (httpHost[level - 1] == 'com') {
		if (httpHost[level - 2] == 'shakuro') {
			if (level == 3) {
				isUserDomain = false;
			} else {
				isUserDomain = true;
			}
		} else {
			if (level == 2) {
				isUserDomain = false;
			} else {
				isUserDomain = true;
			}
		}
	} else if (httpHost[level - 1] == 'localhost') {
		if (level == 2) {
			isUserDomain = false;
		} else {
			isUserDomain = true;
		}
	}
	
	if (isUserDomain) {
		httpHost = httpHost.slice(1);
	}
	return httpHost.join('.');
}
function uStatic(path, protocol, secondLevelDomain, topSite) {
	protocol = 'http'; //stub

	if (typeof topSite != 'undefined' && topSite) {
		if (siteTopDomain == 'cghub.com' && topSite == 'cgdb') {
			topSite = 'cgdb.org';
		} else if (siteTopDomain == 'cgdb.org' && topSite == 'cghub') {
			topSite = 'cghub.com';
		} else {
			var def = siteTopDomain.split('.');
			def = def[0];
			topSite = siteTopDomain.replace(def, topSite);
		}
	} else {
		topSite = siteTopDomain;
	}

	if (typeof secondLevelDomain == 'undefined' || !secondLevelDomain) {
		return protocol+'://'+topSite+path;
	} else {
		return protocol+'://'+secondLevelDomain+'.'+topSite+path;
	}
}
var siteTopDomain = getTopDomain();





/**
 * pluralize word depending on count
 *
 * @author bliss
 */
function plur(count, plur, sing) {
	if (typeof plur == 'undefined') {
		plur = 's';
	}
	if (typeof sing == 'undefined') {
		sing = '';
	}

	if(count <= 0 || count > 1) {
		return plur;
	} else{
		return sing;
	}
}


jQuery.fn.getSelectedText = function() {
  var a;
  this.each(function() {
    if (this.tagName == 'SELECT') {
      var selectElement = this;
      a = selectElement.options[selectElement.options.selectedIndex].text;
    }
  });
  return a;
}

$.fn.ajaxSubmit = function(e) {
  /* Change a form's submission type to ajax */
  this.submit(function(){
    var params = {};
    $(this)
    .find("input:checked, input[type='text'], input[type='file'], input[type='hidden'], input[type='password'], input[type='submit'], option:selected, textarea")
    .filter(":enabled")
    .each(function() {
      params[ this.name || this.id || this.parentNode.name || this.parentNode.id ] = this.value;
    });
    $("body").addClass("curWait");

    $.post(this.getAttribute("action") + "?call=ajax", params, function(xml){
      $("body").removeClass("curWait");
      strError = "Unable to submit form. Please try again later.";
      oFocus = null;

      strRedirect = $('#redirecturl', $(xml)).text();
      strError = $('#error', $(xml)).text();
      strMsg = $('#msg', $(xml)).text();
      msgDiv = $('#msgdiv', $(xml)).text();
      oFocus = $('#focus', $(xml)).text();

      if (strError.length > 0) {
        var reg = new RegExp('(\|)(.+)', 'g');
        $("div.formErrors").html("<h3>Error<\/h3><ul><li>" + strError.replace(reg, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
      } else {
        if (strError.length == 0 && strRedirect.length > 0) {
          window.location = strRedirect;
        }
        if (strMsg.length > 0 && msgDiv.length > 0) {
          $("div."+msgDiv).html("<ul><li>" + strMsg.replace(reg, "<li>$2<\/li>") + "<\/ul>").filter(":hidden").fadeIn("normal");
        }
      }
      if (oFocus) $("#" + oFocus).get(0).focus();

    });
    return false;
  });

  return this;
}
/* example: <AjaxResponse error="&#9;Password is a reqiured field.&#10;&#9;Name is a reqiured field.&#10;&#9;Location is a reqiured field.&#10;" focus="pwdAccountPassword" redirecturl="formSubmissionSuccess.php" /> */

/*$.fn.highQualityImage = function(lowSrc, highSrc){
  thisObject = $(this);

  thisObject.css('background-image', 'url('+lowSrc+')');

  return this.each(function(){
    var i = new Image();
    i.src = highSrc;
    $(i).hide();
    thisObject.after(i);
    i.onload = function() {
      thisObject.css('background-image', 'url('+highSrc+')');
    };
  });
} */

function createCookie(name,value,days) {
  if (days) {
    var date = new Date();
    date.setTime(date.getTime()+(days*24*60*60*1000));
    var expires = "; expires="+date.toGMTString();
  }
  else var expires = "";
  document.cookie = name+"="+value+expires+"; path=/; domain=."+siteTopDomain;
}
function readCookie(name) {
  var nameEQ = name + "=";
  var ca = document.cookie.split(';');
  for(var i=0;i < ca.length;i++) {
    var c = ca[i];
    while (c.charAt(0)==' ') c = c.substring(1,c.length);
    if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
  }
  return null;
}
function eraseCookie(name) {
  createCookie(name,"",-1);
}

function setBackgroundColor(id, background) {
  setTimeout('$("#'+id+'").css("background-color", "'+background+'")', 50);
}

/*--------------------------- on ready --------------------------*/

function changeSort(select) {
  var sort = $(select).val();

  if (sort == 0) {
    sort = '';
  } else if(sort.indexOf(' ') != -1) {
    sort = 'sort:'+sort.substr(0, sort.indexOf(' '))+'/'+'direction:'+sort.substr(sort.indexOf(' ') + 1);
  } else {
    sort = 'sort:'+sort;
  }

  var currentLocation = location.href;

  var reg = new RegExp('http://([^/]*)/');
  currentLocation = currentLocation.replace(reg, '/');
  var reg = new RegExp('(sort:[^/]*)');
  currentLocation = currentLocation.replace(reg, '');
  var reg = new RegExp('(direction:[^/]*)');
  currentLocation = currentLocation.replace(reg, '');
  var reg = new RegExp('\/\/', 'g');
  currentLocation = currentLocation.replace(reg, '/');

  if (currentLocation[currentLocation.length - 1] != '/') {
    currentLocation += '/';
  }

  cghub.redirect(currentLocation+sort);
}

/*function changeViewType(checkbox) {
  var checked = $(checkbox).attr('checked') ? true : false;

  if (checked) {
    var view = '';
  } else {
    var view = 'view:simple';
  }

  var currentLocation = location.href;

  reg = new RegExp('http://([^/]*)/');
  currentLocation = currentLocation.replace(reg, '/');
  reg = new RegExp('(view:[^/]*)');
  currentLocation = currentLocation.replace(reg, '');

  if (currentLocation[currentLocation.length - 1] != '/') {
    currentLocation += '/';
  }

  location.href = currentLocation+view;
}*/


//---------------

var cghub = new Object();
var site = cghub;

cghub.url = {};

cghub.url.removeProtocolAndHost = function(url) {
    var reg = new RegExp('https?://([^/]*)/');
    return url.replace(reg, '/');
};

cghub.url.removeParams = function (url) {
  url = cghub.url.removeProtocolAndHost(url);

  var reg = new RegExp('([^/]+:[^/]+)');
  url = url.replace(reg, '');

  url = cghub.url.removeGetParams(url);
  url = cghub.url.removeHash(url);

  url = url.replace(/\/\//g, '/');

  return url;
};
cghub.url.removeGetParams = function (url) {
  var reg = new RegExp('\\?.*');
  url = url.replace(reg, '');
  return url;
};
cghub.url.removeHash = function(url) {
	if (url.indexOf('#') == -1) {
		return url;
	}

	return url.substr(0, url.indexOf('#'));
};

cghub.url.current = function(removeParams) {
  var currentLocation = document.location.href;

  if (typeof removeParams == 'undefined') {
    var removeParams = true;
  }

  if (removeParams) {
    return cghub.url.removeParams(currentLocation);
  } else {
    return currentLocation;
  }
};
cghub.url.getNamedParam = function(url, name, defaultValue) {
  var reg = new RegExp(name+':([^/\?]+)');
  var match = url.match(reg);
  if (match === null || typeof match[1] == 'undefined') {
    if (typeof defaultValue != 'undefined') {
      return defaultValue;
    } else {
      return null;
    }
  } else {
    return match[1];
  }
};
cghub.url.changeNamedParam = function(url, name, value) {
  var currentValue = cghub.url.getNamedParam(url, name);
  if (currentValue !== null) {
    return url.replace(name+':'+currentValue, name+':'+value);
  } else {
    if (url.indexOf('?') == -1) {
      if (url.charAt(url.length - 1) != '/') {
        url += '/'; //last must be slash
      }
      return url+name+':'+value+'/';
    } else {
      var start = url.substr(0, url.indexOf('?'));
      var end = url.substr(url.indexOf('?'));

      if (start.charAt(start.length - 1) != '/') {
        start += '/'; //last must be slash
      }
      return start+name+':'+value+'/'+end;
    }
  }
};
cghub.url.removeNamedParam = function(url, name) {
	var reg = new RegExp('/'+name+':([^/\?]*)/');
	var match = url.match(reg);
	if (match !== null || typeof match[1] != 'undefined') {
		return url.replace('/'+name+':'+match[1]+'/', '/');
	} else {
		return url;
	}
};

cghub.url.getGetParam = function(url, name, defaultValue) {
  var reg = new RegExp('(\\?|&)'+name+'=([^&#]+)');
  var match = url.match(reg);
  if (match === null || typeof match[2] == 'undefined') {
    if (typeof defaultValue != 'undefined') {
      return defaultValue;
    } else {
      return null;
    }
  } else {
    return match[2];
  }
};

cghub.url.addGetParam = function(url, name, value) {
    if (url.indexOf('?') == -1) {
        if (url.indexOf('#') == -1) {
            return url+'?'+name+'='+value;
        } else {
            return url.substr(0, url.indexOf('#'))+'?'+name+'='+value+'#'+url.substr(url.indexOf('#') + 1);
        }
    } else {
        return url.substr(0, url.indexOf('?'))+'?'+name+'='+value+'&'+url.substr(url.indexOf('?') + 1);
    }
};

cghub.url.getReferer = function() {
  if (cghub.url.getGetParam(document.location.href, 'from') !== null) {
    return cghub.url.getGetParam(document.location.href, 'from');
  }
  if ($('input[name^="refer"]').length > 0) {
    return cghub.url.removeGetParams($('input[name^="refer"]').val());
  }

  return null;
};


cghub.invalidateFields = function(fields){
  $('.error-message').remove();

  var invalidate = function(selector, validationError){
    $(selector).after('<div class="error-message">'+validationError+'</div>');
  };
  for (field in fields) {
    if (field.indexOf('.') != -1) {
      var exploded = field.split('.');
      var name = 'data['+exploded[0]+']['+exploded[1]+']';
      if (exploded.length == 3) {
        name += '['+exploded[2]+']';
      }
      //console.log(name);

      var validInputTypes = ["submit", "reset", "radio", "password", "image", "file", "checkbox", "button", "text"];
      var inputSelector = '';
      validInputTypes.foreach(function(key, value){
        inputSelector += 'input[name="'+name+'"][type="'+value+'"],';
      });

      invalidate(inputSelector+'textarea[name="'+name+'"],select[name="'+name+'"]', fields[field]);
    } else {
      //@todo
    }
  }
};

cghub.tree = {
  'moveElementData': {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}}
};

cghub.tree.moveElement = function(pk, name, moveUrl) {
  //last slash
  if (moveUrl.charAt(moveUrl.length - 1) != '/') {
    moveUrl += '/';
  }

  if (cghub.tree.moveElementData.from.name == '') {
    if (pk == 0) {
      return;
    }
    cghub.tree.moveElementData.from = {'pk':pk, 'name':name};
    alert("You have selected '"+name+"' element to move.\n Now select destination element.");
  } else if (cghub.tree.moveElementData.to.name == '') {
    cghub.tree.moveElementData.to = {'pk':pk, 'name':name};
    var res = confirm("Move element '"+cghub.tree.moveElementData.from.name+"' to '"+cghub.tree.moveElementData.to.name+"'?");
    if (res) {
      moveUrl += cghub.tree.moveElementData.from.pk+'/'+cghub.tree.moveElementData.to.pk+'/';
      $.ajax({
        'url':moveUrl,
        'type':'GET',
        'dataType':'json',
        'success':function(response){
          if (response.result == 'success') {
            cghub.refreshPage(true);
            //document.location.reload(false);
          } else {
            alert(response.message);
          }
        },
        'cache':false
      });
    }
    cghub.tree.moveElementData = {'from':{'pk':0,'name':''}, 'to':{'pk':0,'name':''}}; //empty
  }
};


cghub.user = {
  'id':readCookie('userId') ? parseInt(readCookie('userId')) : null,
  'avatarUrl': {
    'large':null,
    'thumb':null
  }
};

cghub.user.liveAvatarUrl = function() {
  if (cghub.user.id === null || cghub.user.avatarUrl.thumb === null || cghub.user.avatarUrl.large === null) {
    return false;
  }

  $('img[longdesc^="avatar_'+cghub.user.id+'_"]').each(function(){
    if (this.src.indexOf('thumb') != -1 || this.src.indexOf('/img/no_avatar.gif') != -1) {
      this.src = cghub.user.avatarUrl.thumb;//+'?_='+Math.random();
    } else {
      this.src = cghub.user.avatarUrl.large;//+'?_='+Math.random();
    }
  });
};

cghub.user.isLoggedIn = function(){
    return cghub.user.id !== null && cghub.user.id != 0;
    //return $('#editprofile_popup_div').length > 0 || $('#editprofile_li').length;
};

cghub.rate = function (model, parentId, rate) {
  $.ajax({
    'type': 'POST',
    'url': '/rates/rate/'+model+'/'+parentId+'/'+rate+'/?call=ajax',
    'success': function(response){
      if (response.result == 'error') {
        $("p#rate_text_"+parentId).html(response.message).filter(":hidden").fadeIn("normal");
      } else {
        $("p#rate_text_"+parentId).html(response.message).filter(":hidden").fadeIn("normal");
        $('.current-rating_'+parentId).css('width', Math.round(response.rate * 150 / 5)+'px');
      }
    },
    'dataType':'json'
  });
  return false;
};
cghub.like = function (link) {
	var model = $(link).attr('rel').split('_')[0];
	var parentId = $(link).attr('rel').split('_')[1];

	var count = parseInt($(link).prev('span').html().trim());

	if ($(link).hasClass('done')) {
		var action = 'unlike';
		$(link).prev('span').html(count - 1);
	} else {
		var action = 'like';
		$(link).prev('span').html(count + 1);
	}

	$.ajax({
		'type':'POST',
		'url':'/'+action+'/'+model+'/'+parentId+'/?call=ajax',
		'cache':false,
		'dataType':'json',
		'success':function(response){
			if (response.result == 'success') {
				$(link).toggleClass('done');
				$(link).prev('span').html(response.count);
				$(link).next('span').html(response.users);
			} else {
				alert(response.message);
				/*
				var errorDiv = $('#likeErrorBox');
				if (errorDiv.length == 0) {
					var errorDiv = $('<div></div>').attr('id', 'likeErrorBox').css({'display':'none'});
					var errorSpan = $('<span><h1></h1></span>');
					errorDiv.append(errorSpan);
					$('body').append(errorDiv);
				}
				errorDiv.ready(function(){
					errorDiv.find('h1').html(response.message);
				});
	
				setTimeout(function(){
					tb_show('Like', '?#TB_inline=true;inlineId=likeErrorBox');
				}, 100);
				*/
			}
		}
	});
};
cghub.favorite = function(link) {
	var model = $(link).attr('rel').split('_')[0];
	var parentId = $(link).attr('rel').split('_')[1];

	$(link).html('Please wait...');

	if ($(link).hasClass('ed')) {
		var action = 'delFavorite';
		var message = 'Removed from favs';
	} else {
		var action = 'addFavorite';
		var message = 'Favorite';
	}

	$.ajax({
		'type':'POST',
		'url':'/favorites/'+action+'/'+model+'/'+parentId+'/?call=ajax',
		'cache':false,
		'dataType':'json',
		'success':function(response){
			if (response.result == 'success') {
				$(link).toggleClass('ed');
				$(link).html(message);
				//$(link).prev('span').html(response.count);
				$(link).next('span').html(response.users);
			} else {
				alert(response.message);
			}
		}
	});
};
cghub.subscribe = function(link) {
	var model = $(link).attr('rel').split('_')[0];
	var parentId = $(link).attr('rel').split('_')[1];

	$(link).html('Please wait...');

	if ($(link).hasClass('ed')) {
		var action = 'unsubscribe';
		var message = 'Unsubscribed';
	} else {
		var action = 'subscribe';
		var message = 'Subscribed';
	}

	$.ajax({
		'type':'POST',
		'url':'/subscribes/'+action+'/'+model+'/'+parentId+'/?call=ajax',
		'cache':false,
		'dataType':'json',
		'success':function(response){
			if (response.result == 'success') {
				$(link).toggleClass('ed');
				$(link).html(message);
				//$(link).prev('span').html(response.count);
				$(link).next('span').html(response.users);
			} else {
				alert(response.message);
			}
		}
	});
};
cghub.follow = function(link) {
	var followedUserId = $(link).attr('rel');

	$(link).html('Please wait...');

	if ($(link).hasClass('ed')) {
		var action = 'unfollow';
		var message = 'Unfollowed';
	} else {
		var action = 'follow';
		var message = 'Followed';
	}

	$.ajax({
		'type':'POST',
		'url':'/followers/'+action+'/'+followedUserId+'/?call=ajax',
		'cache':false,
		'dataType':'json',
		'success':function(response){
			if (response.result == 'success') {
				$(link).toggleClass('ed');
				$(link).html(message);

				$(link).next('span').html(response.users);
			} else {
				alert(response.message);
			}
		}
	});
};


cghub.uiColor = {};
cghub.uiColor.white = function(){
  if ($('#ui_color').length > 0) {
    var selector = '#ui_color';
  } else {
    var selector = 'body';
  }

  $(selector).removeClass('darkui');
  $.ajax({
    'type':'POST',
    'url':'/profiles/setUiColor/white/?call=ajax'
  });
  return false;
};
cghub.uiColor.black = function(){
  if ($('#ui_color').length > 0) {
    var selector = '#ui_color';
  } else {
    var selector = 'body';
  }

  $(selector).addClass('darkui');
  $.ajax({
    'type':'POST',
    'url':'/profiles/setUiColor/black/?call=ajax'
  });
  return false;
};



cghub.autocomplete = {};
/**
 * @deprecated
 */
cghub.autocomplete.multipleGetValue = function(element, itemFromAjax) {
  //console.log('--------------- get -----------------', element, itemFromAjax);

  element = $(element);

  if (typeof itemFromAjax != 'undefined' && typeof itemFromAjax.value != 'undefined') {
    var previous = $.data(element[0], 'previous');
    if (!previous) {
      previous = [];
    }
    var current = $(element).val().split(',');
    current.map(function(elem, key){
      current[key] = elem.trim();
    });

    for (var i = 0; i < current.length - 1; i++) { //do not include last incomplete word
      previous.push(current[i]);
    }

    previous = previous.unique();

    previous = previous.clean('');
    //				console.error('stored', previous);
    $.data(element[0], 'previous', previous);


    return itemFromAjax.value;
  }


  var val = $(element).val().trim();

  //			console.log('val', val);

  if (val.indexOf(',') == -1) {
    return val;
  }

  var words = val.split(',');
  words.map(function(elem, key){
    words[key] = elem.trim();
  });

  //			console.info(words);

  return words[words.length - 1];
};
/**
 * @deprecated
 */
cghub.autocomplete.multipleSetValue = function(element, value, fromMethod) {
  //console.log('--------------- set -----------------', element, value, fromMethod);

  if (fromMethod == 'blur') {
    value = '';
  }

  var val = htmlspecialchars_decode(html_entity_decode(html_entity_decode( value ))).trim();

  //			console.log('val', val);



  if (val.indexOf(',') != -1) {
    var words = val.split(',');
    words.map(function(elem, key){
      words[key] = elem.trim();
    });
    val = words[words.length - 1];
  }

  var prevData = $.data(element[0], 'previous');
  if (typeof prevData != 'undefined' && prevData !== null) {
    var previous = [];
    for (var i = 0; i < prevData.length; i++) {
      previous.push(prevData[i]);
    }
    previous.push(val);
    previous = previous.unique();
  } else {
    //				console.log('1111111');
    var previous = [val];
  }

  //			console.warn('previous', previous);

  if (fromMethod == 'selected') {
    //				console.error('stored', previous);
    previous = previous.clean('');
    $.data(element[0], 'previous', previous);
  }

  val = previous.join(', ');
  val += ',';

  //			console.info('set', '__', value, '__', fromMethod, '__', val);

  element.val(val);
  element.each(function(){
    setSelectionRange(this, val.length, val.length);
    this.focus();
  });
  return true;
};


$.fn.autocompleteMultiple = function(opts){
	if (typeof opts == 'undefined') {
		opts = {};
	}

	function split(val) {
		return val.split(/,\s*/);
	}
	function extractLast(term) {
		return split(term).pop();
	}

	var cache = {}, lastXhr;


	var defOpts = {
		'minLength': 1,
		'appendTo': this.parent(),
		'search': function() {
			// custom minLength
			var term = extractLast(this.value);
			if (term.length < 2) {
				return false;
			}
		},
		'focus': function() {
			// prevent value inserted on focus
			return false;
		},
		'select': function(event, ui) {
			var terms = split(this.value);
			// 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;
		}
	};

	//cache requests
	if (typeof opts.source == 'string') {
		var source = opts.source;
		opts.source = function(request, response) {
			var term = extractLast(request.term);
			if (term in cache) {
				response(cache[term]);
				return;
			}

			lastXhr = $.getJSON(source, {'term':term}, function(data, status, xhr) {
				cache[term] = data;
				if (xhr === lastXhr) {
					response(data);
				}
			});
		}
	}

	$.extend(defOpts, opts);
	opts = defOpts;

	// don't navigate away from the field on tab when selecting an item
	return this.bind("keydown", function(event) {
			if (event.keyCode === $.ui.keyCode.TAB &&
					$(this).data("autocomplete").menu.active) {
				event.preventDefault();
			}
		})
		.autocomplete(opts);
};



var checkboxTriggerClickEvent = jQuery.Event("logged");


$(function(){

	//search box
	$('#inputSearchText').focus(function(){
		var val = $(this).val();
//		alert(val.substr(0, 6));
		if (val.substr(0, 6) == 'Search') {
			$(this).val('');
		}
	});


	//custom checkboxes
	function checkboxChangedHandler(event) {
		var cb = $(event.data.cb);
		var toggle = event.data.toggle;

		var a = cb.next('a');
		if (cb.is(':checked')) {
			if (toggle) {
				cb.removeAttr('checked');
				cb.trigger('change');
				a.attr('class', 'uncheck');
			} else {
				a.attr('class', 'check');
			}
		} else {
			if (toggle) {
				cb.attr('checked', true);
				cb.trigger('change');
				a.attr('class', 'check');
			} else {
				a.attr('class', 'uncheck');
			}
		}
		return false;
	}
	$('input[type="checkbox"]').each(function () {
	    this.style.display = 'none';
	    if ($(this).is(':checked')) {
	        $(this).after('<a class="check"></a>');
	    } else {
	        $(this).after('<a class="uncheck"></a>');
	    }
	    $(this).bind('change', {'cb':this, 'toggle':false}, function(event){checkboxChangedHandler(event);return true;})
			    .delay(100)
			    .next('a')
			    .bind('click', {'cb':this, 'toggle':true}, checkboxChangedHandler);
	});


	$('a.like').click(function(){
		cghub.like(this);
		return false;
	}).each(function(){
		if (typeof cghub.user.id == 'undefined' || !cghub.user.id) {
			return true; //continue
		}

		var users = $(this).next('span').html().split(',');

		var users = users.map(function(num){ return parseInt(num, 10); }); //cannot use parseInt directly, see http://stackoverflow.com/questions/262427/javscript-array-map-and-parseint

		if (users.indexOf(parseInt(cghub.user.id)) != -1) {
			$(this).addClass('done');
		}
	});
	$('a.favorite').click(function(){
		cghub.favorite(this);
		return false;
	}).each(function(){
		if (typeof cghub.user.id == 'undefined' || !cghub.user.id) {
			return true; //continue
		}

		var users = $(this).next('span').html().split(',');

		var users = users.map(function(num){ return parseInt(num, 10); }); //cannot use parseInt directly, see http://stackoverflow.com/questions/262427/javscript-array-map-and-parseint

		if (users.indexOf(parseInt(cghub.user.id)) != -1) {
			$(this).addClass('ed');
			$(this).html('Favorite');
		}
	});
	$('a.subscribe').click(function(){
		cghub.subscribe(this);
		return false;
	}).each(function(){
		if (typeof cghub.user.id == 'undefined' || !cghub.user.id) {
			return true; //continue
		}

		var users = $(this).next('span').html().split(',');

		var users = users.map(function(num){ return parseInt(num, 10); }); //cannot use parseInt directly, see http://stackoverflow.com/questions/262427/javscript-array-map-and-parseint

		if (users.indexOf(parseInt(cghub.user.id)) != -1) {
			$(this).addClass('ed');
			$(this).html('Subscribed');
		}
	});
	$('a.follow').click(function(){
		cghub.follow(this);
		return false;
	}).each(function(){
		if (typeof cghub.user.id == 'undefined' || !cghub.user.id) {
			return true; //continue
		}

		var users = $(this).next('span').html().split(',');

		var users = users.map(function(num){ return parseInt(num, 10); }); //cannot use parseInt directly, see http://stackoverflow.com/questions/262427/javscript-array-map-and-parseint

		if (users.indexOf(parseInt(cghub.user.id)) != -1) {
			$(this).addClass('ed');
			$(this).html('Followed');
		}
	});


	$('#mosaicLinks').prevAll('h3:first').find('img[alt="open"]').myPopup({
		'popupElem':$('#mosaicLinks'),
		'onShow':function(){
			var mosaicInfo =  $('#mosaicUl').attr('title');
			if (mosaicInfo) {
				$('#mosaicUl').data('mosaicInfo', mosaicInfo).attr('title', '');
			} else {
				mosaicInfo = $('#mosaicUl').data('mosaicInfo');
			}
			
			var mosaicGroupCurrent = mosaicInfo.split(':')[0];
			var mosaicTypeCurrent = mosaicInfo.split(':')[1];

			$('#mosaicLinks a').removeClass('current');
			$('#mosaicLinks a[rel="type='+mosaicTypeCurrent+'"]').addClass('current');
			$('#mosaicLinks a[rel="group='+mosaicGroupCurrent+'"]').addClass('current');
		},
		'timeout': 1000
	});

	
  setTimeout(function(){
      if (!cghub.user.isLoggedIn()) {
          $('#forum_menu_my_posts_threads_subscribed').hide();
      }
  }, 3000);

  var cookie = readCookie('liveAvatarUrl');
  if (cookie == null) {
	  return false;
  }

  cookie = JSON.parse(unescape(cookie));

  cghub.user.id = cookie.id;
  cghub.user.avatarUrl = cookie.avatarUrl;

  cghub.user.liveAvatarUrl();


});



