/* JScompressor online - http://jscompress.com/ */

/*!
 * jQuery UI 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI
 */
(function(c,j){function k(a){return!c(a).parents().andSelf().filter(function(){return c.curCSS(this,"visibility")==="hidden"||c.expr.filters.hidden(this)}).length}c.ui=c.ui||{};if(!c.ui.version){c.extend(c.ui,{version:"1.8.4",plugin:{add:function(a,b,d){a=c.ui[a].prototype;for(var e in d){a.plugins[e]=a.plugins[e]||[];a.plugins[e].push([b,d[e]])}},call:function(a,b,d){if((b=a.plugins[b])&&a.element[0].parentNode)for(var e=0;e<b.length;e++)a.options[b[e][0]]&&b[e][1].apply(a.element,d)}},contains:function(a,
b){return document.compareDocumentPosition?a.compareDocumentPosition(b)&16:a!==b&&a.contains(b)},hasScroll:function(a,b){if(c(a).css("overflow")==="hidden")return false;b=b&&b==="left"?"scrollLeft":"scrollTop";var d=false;if(a[b]>0)return true;a[b]=1;d=a[b]>0;a[b]=0;return d},isOverAxis:function(a,b,d){return a>b&&a<b+d},isOver:function(a,b,d,e,h,i){return c.ui.isOverAxis(a,d,h)&&c.ui.isOverAxis(b,e,i)},keyCode:{ALT:18,BACKSPACE:8,CAPS_LOCK:20,COMMA:188,COMMAND:91,COMMAND_LEFT:91,COMMAND_RIGHT:93,
CONTROL:17,DELETE:46,DOWN:40,END:35,ENTER:13,ESCAPE:27,HOME:36,INSERT:45,LEFT:37,MENU:93,NUMPAD_ADD:107,NUMPAD_DECIMAL:110,NUMPAD_DIVIDE:111,NUMPAD_ENTER:108,NUMPAD_MULTIPLY:106,NUMPAD_SUBTRACT:109,PAGE_DOWN:34,PAGE_UP:33,PERIOD:190,RIGHT:39,SHIFT:16,SPACE:32,TAB:9,UP:38,WINDOWS:91}});c.fn.extend({_focus:c.fn.focus,focus:function(a,b){return typeof a==="number"?this.each(function(){var d=this;setTimeout(function(){c(d).focus();b&&b.call(d)},a)}):this._focus.apply(this,arguments)},enableSelection:function(){return this.attr("unselectable",
"off").css("MozUserSelect","")},disableSelection:function(){return this.attr("unselectable","on").css("MozUserSelect","none")},scrollParent:function(){var a;a=c.browser.msie&&/(static|relative)/.test(this.css("position"))||/absolute/.test(this.css("position"))?this.parents().filter(function(){return/(relative|absolute|fixed)/.test(c.curCSS(this,"position",1))&&/(auto|scroll)/.test(c.curCSS(this,"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0):this.parents().filter(function(){return/(auto|scroll)/.test(c.curCSS(this,
"overflow",1)+c.curCSS(this,"overflow-y",1)+c.curCSS(this,"overflow-x",1))}).eq(0);return/fixed/.test(this.css("position"))||!a.length?c(document):a},zIndex:function(a){if(a!==j)return this.css("zIndex",a);if(this.length){a=c(this[0]);for(var b;a.length&&a[0]!==document;){b=a.css("position");if(b==="absolute"||b==="relative"||b==="fixed"){b=parseInt(a.css("zIndex"));if(!isNaN(b)&&b!=0)return b}a=a.parent()}}return 0}});c.each(["Width","Height"],function(a,b){function d(f,g,l,m){c.each(e,function(){g-=
parseFloat(c.curCSS(f,"padding"+this,true))||0;if(l)g-=parseFloat(c.curCSS(f,"border"+this+"Width",true))||0;if(m)g-=parseFloat(c.curCSS(f,"margin"+this,true))||0});return g}var e=b==="Width"?["Left","Right"]:["Top","Bottom"],h=b.toLowerCase(),i={innerWidth:c.fn.innerWidth,innerHeight:c.fn.innerHeight,outerWidth:c.fn.outerWidth,outerHeight:c.fn.outerHeight};c.fn["inner"+b]=function(f){if(f===j)return i["inner"+b].call(this);return this.each(function(){c.style(this,h,d(this,f)+"px")})};c.fn["outer"+
b]=function(f,g){if(typeof f!=="number")return i["outer"+b].call(this,f);return this.each(function(){c.style(this,h,d(this,f,true,g)+"px")})}});c.extend(c.expr[":"],{data:function(a,b,d){return!!c.data(a,d[3])},focusable:function(a){var b=a.nodeName.toLowerCase(),d=c.attr(a,"tabindex");if("area"===b){b=a.parentNode;d=b.name;if(!a.href||!d||b.nodeName.toLowerCase()!=="map")return false;a=c("img[usemap=#"+d+"]")[0];return!!a&&k(a)}return(/input|select|textarea|button|object/.test(b)?!a.disabled:"a"==
b?a.href||!isNaN(d):!isNaN(d))&&k(a)},tabbable:function(a){var b=c.attr(a,"tabindex");return(isNaN(b)||b>=0)&&c(a).is(":focusable")}})}})(jQuery);
;/*!
 * jQuery UI Widget 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Widget
 */
(function(b,j){var k=b.fn.remove;b.fn.remove=function(a,c){return this.each(function(){if(!c)if(!a||b.filter(a,[this]).length)b("*",this).add([this]).each(function(){b(this).triggerHandler("remove")});return k.call(b(this),a,c)})};b.widget=function(a,c,d){var e=a.split(".")[0],f;a=a.split(".")[1];f=e+"-"+a;if(!d){d=c;c=b.Widget}b.expr[":"][f]=function(h){return!!b.data(h,a)};b[e]=b[e]||{};b[e][a]=function(h,g){arguments.length&&this._createWidget(h,g)};c=new c;c.options=b.extend(true,{},c.options);
b[e][a].prototype=b.extend(true,c,{namespace:e,widgetName:a,widgetEventPrefix:b[e][a].prototype.widgetEventPrefix||a,widgetBaseClass:f},d);b.widget.bridge(a,b[e][a])};b.widget.bridge=function(a,c){b.fn[a]=function(d){var e=typeof d==="string",f=Array.prototype.slice.call(arguments,1),h=this;d=!e&&f.length?b.extend.apply(null,[true,d].concat(f)):d;if(e&&d.substring(0,1)==="_")return h;e?this.each(function(){var g=b.data(this,a),i=g&&b.isFunction(g[d])?g[d].apply(g,f):g;if(i!==g&&i!==j){h=i;return false}}):
this.each(function(){var g=b.data(this,a);if(g){d&&g.option(d);g._init()}else b.data(this,a,new c(d,this))});return h}};b.Widget=function(a,c){arguments.length&&this._createWidget(a,c)};b.Widget.prototype={widgetName:"widget",widgetEventPrefix:"",options:{disabled:false},_createWidget:function(a,c){b.data(c,this.widgetName,this);this.element=b(c);this.options=b.extend(true,{},this.options,b.metadata&&b.metadata.get(c)[this.widgetName],a);var d=this;this.element.bind("remove."+this.widgetName,function(){d.destroy()});
this._create();this._init()},_create:function(){},_init:function(){},destroy:function(){this.element.unbind("."+this.widgetName).removeData(this.widgetName);this.widget().unbind("."+this.widgetName).removeAttr("aria-disabled").removeClass(this.widgetBaseClass+"-disabled ui-state-disabled")},widget:function(){return this.element},option:function(a,c){var d=a,e=this;if(arguments.length===0)return b.extend({},e.options);if(typeof a==="string"){if(c===j)return this.options[a];d={};d[a]=c}b.each(d,function(f,
h){e._setOption(f,h)});return e},_setOption:function(a,c){this.options[a]=c;if(a==="disabled")this.widget()[c?"addClass":"removeClass"](this.widgetBaseClass+"-disabled ui-state-disabled").attr("aria-disabled",c);return this},enable:function(){return this._setOption("disabled",false)},disable:function(){return this._setOption("disabled",true)},_trigger:function(a,c,d){var e=this.options[a];c=b.Event(c);c.type=(a===this.widgetEventPrefix?a:this.widgetEventPrefix+a).toLowerCase();d=d||{};if(c.originalEvent){a=
b.event.props.length;for(var f;a;){f=b.event.props[--a];c[f]=c.originalEvent[f]}}this.element.trigger(c,d);return!(b.isFunction(e)&&e.call(this.element[0],c,d)===false||c.isDefaultPrevented())}}})(jQuery);
;/*
 * jQuery UI Position 1.8.4
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Position
 */
(function(c){c.ui=c.ui||{};var m=/left|center|right/,n=/top|center|bottom/,p=c.fn.position,q=c.fn.offset;c.fn.position=function(a){if(!a||!a.of)return p.apply(this,arguments);a=c.extend({},a);var b=c(a.of),d=(a.collision||"flip").split(" "),e=a.offset?a.offset.split(" "):[0,0],g,h,i;if(a.of.nodeType===9){g=b.width();h=b.height();i={top:0,left:0}}else if(a.of.scrollTo&&a.of.document){g=b.width();h=b.height();i={top:b.scrollTop(),left:b.scrollLeft()}}else if(a.of.preventDefault){a.at="left top";g=h=
0;i={top:a.of.pageY,left:a.of.pageX}}else{g=b.outerWidth();h=b.outerHeight();i=b.offset()}c.each(["my","at"],function(){var f=(a[this]||"").split(" ");if(f.length===1)f=m.test(f[0])?f.concat(["center"]):n.test(f[0])?["center"].concat(f):["center","center"];f[0]=m.test(f[0])?f[0]:"center";f[1]=n.test(f[1])?f[1]:"center";a[this]=f});if(d.length===1)d[1]=d[0];e[0]=parseInt(e[0],10)||0;if(e.length===1)e[1]=e[0];e[1]=parseInt(e[1],10)||0;if(a.at[0]==="right")i.left+=g;else if(a.at[0]==="center")i.left+=
g/2;if(a.at[1]==="bottom")i.top+=h;else if(a.at[1]==="center")i.top+=h/2;i.left+=e[0];i.top+=e[1];return this.each(function(){var f=c(this),k=f.outerWidth(),l=f.outerHeight(),j=c.extend({},i);if(a.my[0]==="right")j.left-=k;else if(a.my[0]==="center")j.left-=k/2;if(a.my[1]==="bottom")j.top-=l;else if(a.my[1]==="center")j.top-=l/2;j.left=parseInt(j.left);j.top=parseInt(j.top);c.each(["left","top"],function(o,r){c.ui.position[d[o]]&&c.ui.position[d[o]][r](j,{targetWidth:g,targetHeight:h,elemWidth:k,
elemHeight:l,offset:e,my:a.my,at:a.at})});c.fn.bgiframe&&f.bgiframe();f.offset(c.extend(j,{using:a.using}))})};c.ui.position={fit:{left:function(a,b){var d=c(window);b=a.left+b.elemWidth-d.width()-d.scrollLeft();a.left=b>0?a.left-b:Math.max(0,a.left)},top:function(a,b){var d=c(window);b=a.top+b.elemHeight-d.height()-d.scrollTop();a.top=b>0?a.top-b:Math.max(0,a.top)}},flip:{left:function(a,b){if(b.at[0]!=="center"){var d=c(window);d=a.left+b.elemWidth-d.width()-d.scrollLeft();var e=b.my[0]==="left"?
-b.elemWidth:b.my[0]==="right"?b.elemWidth:0,g=-2*b.offset[0];a.left+=a.left<0?e+b.targetWidth+g:d>0?e-b.targetWidth+g:0}},top:function(a,b){if(b.at[1]!=="center"){var d=c(window);d=a.top+b.elemHeight-d.height()-d.scrollTop();var e=b.my[1]==="top"?-b.elemHeight:b.my[1]==="bottom"?b.elemHeight:0,g=b.at[1]==="top"?b.targetHeight:-b.targetHeight,h=-2*b.offset[1];a.top+=a.top<0?e+b.targetHeight+h:d>0?e+g+h:0}}}};if(!c.offset.setOffset){c.offset.setOffset=function(a,b){if(/static/.test(c.curCSS(a,"position")))a.style.position=
"relative";var d=c(a),e=d.offset(),g=parseInt(c.curCSS(a,"top",true),10)||0,h=parseInt(c.curCSS(a,"left",true),10)||0;e={top:b.top-e.top+g,left:b.left-e.left+h};"using"in b?b.using.call(a,e):d.css(e)};c.fn.offset=function(a){var b=this[0];if(!b||!b.ownerDocument)return null;if(a)return this.each(function(){c.offset.setOffset(this,a)});return q.call(this)}}})(jQuery);

/*
 * jQuery UI Autocomplete 1.8.6
 *
 * Copyright 2010, AUTHORS.txt (http://jqueryui.com/about)
 * Dual licensed under the MIT or GPL Version 2 licenses.
 * http://jquery.org/license
 *
 * http://docs.jquery.com/UI/Autocomplete
 *
 * Depends:
 *	jquery.ui.core.js
 *	jquery.ui.widget.js
 *	jquery.ui.position.js
 */
(function(e){e.widget("ui.autocomplete",{options:{appendTo:"body",delay:300,minLength:1,position:{my:"left top",at:"left bottom",collision:"none"},source:null},_create:function(){var a=this,b=this.element[0].ownerDocument,f;this.element.addClass("ui-autocomplete-input").attr("autocomplete","off").attr({role:"textbox","aria-autocomplete":"list","aria-haspopup":"true"}).bind("keydown.autocomplete",function(c){if(!(a.options.disabled||a.element.attr("readonly"))){f=false;var d=e.ui.keyCode;switch(c.keyCode){case d.PAGE_UP:a._move("previousPage",
c);break;case d.PAGE_DOWN:a._move("nextPage",c);break;case d.UP:a._move("previous",c);c.preventDefault();break;case d.DOWN:a._move("next",c);c.preventDefault();break;case d.ENTER:case d.NUMPAD_ENTER:if(a.menu.active){f=true;c.preventDefault()}case d.TAB:if(!a.menu.active)return;a.menu.select(c);break;case d.ESCAPE:a.element.val(a.term);a.close(c);break;default:clearTimeout(a.searching);a.searching=setTimeout(function(){if(a.term!=a.element.val()){a.selectedItem=null;a.search(null,c)}},a.options.delay);
break}}}).bind("keypress.autocomplete",function(c){if(f){f=false;c.preventDefault()}}).bind("focus.autocomplete",function(){if(!a.options.disabled){a.selectedItem=null;a.previous=a.element.val()}}).bind("blur.autocomplete",function(c){if(!a.options.disabled){clearTimeout(a.searching);a.closing=setTimeout(function(){a.close(c);a._change(c)},150)}});this._initSource();this.response=function(){return a._response.apply(a,arguments)};this.menu=e("<ul></ul>").addClass("ui-autocomplete").appendTo(e(this.options.appendTo||
"body",b)[0]).mousedown(function(c){var d=a.menu.element[0];e(c.target).closest(".ui-menu-item").length||setTimeout(function(){e(document).one("mousedown",function(g){g.target!==a.element[0]&&g.target!==d&&!e.ui.contains(d,g.target)&&a.close()})},1);setTimeout(function(){clearTimeout(a.closing)},13)}).menu({focus:function(c,d){d=d.item.data("item.autocomplete");false!==a._trigger("focus",c,{item:d})&&/^key/.test(c.originalEvent.type)&&a.element.val(d.value)},selected:function(c,d){d=d.item.data("item.autocomplete");
var g=a.previous;if(a.element[0]!==b.activeElement){a.element.focus();a.previous=g;setTimeout(function(){a.previous=g},1)}false!==a._trigger("select",c,{item:d})&&a.element.val(d.value);a.term=a.element.val();a.close(c);a.selectedItem=d},blur:function(){a.menu.element.is(":visible")&&a.element.val()!==a.term&&a.element.val(a.term)}}).zIndex(this.element.zIndex()+1).css({top:0,left:0}).hide().data("menu");e.fn.bgiframe&&this.menu.element.bgiframe()},destroy:function(){this.element.removeClass("ui-autocomplete-input").removeAttr("autocomplete").removeAttr("role").removeAttr("aria-autocomplete").removeAttr("aria-haspopup");
this.menu.element.remove();e.Widget.prototype.destroy.call(this)},_setOption:function(a,b){e.Widget.prototype._setOption.apply(this,arguments);a==="source"&&this._initSource();if(a==="appendTo")this.menu.element.appendTo(e(b||"body",this.element[0].ownerDocument)[0])},_initSource:function(){var a=this,b,f;if(e.isArray(this.options.source)){b=this.options.source;this.source=function(c,d){d(e.ui.autocomplete.filter(b,c.term))}}else if(typeof this.options.source==="string"){f=this.options.source;this.source=
function(c,d){a.xhr&&a.xhr.abort();a.xhr=e.getJSON(f,c,function(g,i,h){h===a.xhr&&d(g);a.xhr=null})}}else this.source=this.options.source},search:function(a,b){a=a!=null?a:this.element.val();this.term=this.element.val();if(a.length<this.options.minLength)return this.close(b);clearTimeout(this.closing);if(this._trigger("search",b)!==false)return this._search(a)},_search:function(a){this.element.addClass("ui-autocomplete-loading");this.source({term:a},this.response)},_response:function(a){if(a&&a.length){a=
this._normalize(a);this._suggest(a);this._trigger("open")}else this.close();this.element.removeClass("ui-autocomplete-loading")},close:function(a){clearTimeout(this.closing);if(this.menu.element.is(":visible")){this._trigger("close",a);this.menu.element.hide();this.menu.deactivate()}},_change:function(a){this.previous!==this.element.val()&&this._trigger("change",a,{item:this.selectedItem})},_normalize:function(a){if(a.length&&a[0].label&&a[0].value)return a;return e.map(a,function(b){if(typeof b===
"string")return{label:b,value:b};return e.extend({label:b.label||b.value,value:b.value||b.label},b)})},_suggest:function(a){this._renderMenu(this.menu.element.empty().zIndex(this.element.zIndex()+1),a);this.menu.deactivate();this.menu.refresh();this.menu.element.show().position(e.extend({of:this.element},this.options.position));this._resizeMenu()},_resizeMenu:function(){var a=this.menu.element;a.outerWidth(Math.max(a.width("").outerWidth(),this.element.outerWidth()))},_renderMenu:function(a,b){var f=
this;e.each(b,function(c,d){f._renderItem(a,d)})},_renderItem:function(a,b){return e("<li></li>").data("item.autocomplete",b).append(e("<a></a>").text(b.label)).appendTo(a)},_move:function(a,b){if(this.menu.element.is(":visible"))if(this.menu.first()&&/^previous/.test(a)||this.menu.last()&&/^next/.test(a)){this.element.val(this.term);this.menu.deactivate()}else this.menu[a](b);else this.search(null,b)},widget:function(){return this.menu.element}});e.extend(e.ui.autocomplete,{escapeRegex:function(a){return a.replace(/[-[\]{}()*+?.,\\^$|#\s]/g,
"\\$&")},filter:function(a,b){var f=new RegExp(e.ui.autocomplete.escapeRegex(b),"i");return e.grep(a,function(c){return f.test(c.label||c.value||c)})}})})(jQuery);
(function(e){e.widget("ui.menu",{_create:function(){var a=this;this.element.addClass("ui-menu ui-widget ui-widget-content ui-corner-all").attr({role:"listbox","aria-activedescendant":"ui-active-menuitem"}).click(function(b){if(e(b.target).closest(".ui-menu-item a").length){b.preventDefault();a.select(b)}});this.refresh()},refresh:function(){var a=this;this.element.children("li:not(.ui-menu-item):has(a)").addClass("ui-menu-item").attr("role","menuitem").children("a").addClass("ui-corner-all").attr("tabindex",
-1).mouseenter(function(b){a.activate(b,e(this).parent())}).mouseleave(function(){a.deactivate()})},activate:function(a,b){this.deactivate();if(this.hasScroll()){var f=b.offset().top-this.element.offset().top,c=this.element.attr("scrollTop"),d=this.element.height();if(f<0)this.element.attr("scrollTop",c+f);else f>=d&&this.element.attr("scrollTop",c+f-d+b.height())}this.active=b.eq(0).children("a").addClass("ui-state-hover").attr("id","ui-active-menuitem").end();this._trigger("focus",a,{item:b})},
deactivate:function(){if(this.active){this.active.children("a").removeClass("ui-state-hover").removeAttr("id");this._trigger("blur");this.active=null}},next:function(a){this.move("next",".ui-menu-item:first",a)},previous:function(a){this.move("prev",".ui-menu-item:last",a)},first:function(){return this.active&&!this.active.prevAll(".ui-menu-item").length},last:function(){return this.active&&!this.active.nextAll(".ui-menu-item").length},move:function(a,b,f){if(this.active){a=this.active[a+"All"](".ui-menu-item").eq(0);
a.length?this.activate(f,a):this.activate(f,this.element.children(b))}else this.activate(f,this.element.children(b))},nextPage:function(a){if(this.hasScroll())if(!this.active||this.last())this.activate(a,this.element.children(".ui-menu-item:first"));else{var b=this.active.offset().top,f=this.element.height(),c=this.element.children(".ui-menu-item").filter(function(){var d=e(this).offset().top-b-f+e(this).height();return d<10&&d>-10});c.length||(c=this.element.children(".ui-menu-item:last"));this.activate(a,
c)}else this.activate(a,this.element.children(".ui-menu-item").filter(!this.active||this.last()?":first":":last"))},previousPage:function(a){if(this.hasScroll())if(!this.active||this.first())this.activate(a,this.element.children(".ui-menu-item:last"));else{var b=this.active.offset().top,f=this.element.height();result=this.element.children(".ui-menu-item").filter(function(){var c=e(this).offset().top-b+f-e(this).height();return c<10&&c>-10});result.length||(result=this.element.children(".ui-menu-item:first"));
this.activate(a,result)}else this.activate(a,this.element.children(".ui-menu-item").filter(!this.active||this.first()?":last":":first"))},hasScroll:function(){return this.element.height()<this.element.attr("scrollHeight")},select:function(a){this._trigger("selected",a,{item:this.active})}})})(jQuery);
;/*

/**
 * jQuery.ScrollTo - Easy element scrolling using jQuery.
 * Copyright (c) 2007-2009 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com
 * Dual licensed under MIT and GPL.
 * Date: 5/25/2009
 * @author Ariel Flesler
 * @version 1.4.2
 *
 * http://flesler.blogspot.com/2007/10/jqueryscrollto.html
 */
;(function(d){var k=d.scrollTo=function(a,i,e){d(window).scrollTo(a,i,e)};k.defaults={axis:'xy',duration:parseFloat(d.fn.jquery)>=1.3?0:1};k.window=function(a){return d(window)._scrollable()};d.fn._scrollable=function(){return this.map(function(){var a=this,i=!a.nodeName||d.inArray(a.nodeName.toLowerCase(),['iframe','#document','html','body'])!=-1;if(!i)return a;var e=(a.contentWindow||a).document||a.ownerDocument||a;return d.browser.safari||e.compatMode=='BackCompat'?e.body:e.documentElement})};d.fn.scrollTo=function(n,j,b){if(typeof j=='object'){b=j;j=0}if(typeof b=='function')b={onAfter:b};if(n=='max')n=9e9;b=d.extend({},k.defaults,b);j=j||b.speed||b.duration;b.queue=b.queue&&b.axis.length>1;if(b.queue)j/=2;b.offset=p(b.offset);b.over=p(b.over);return this._scrollable().each(function(){var q=this,r=d(q),f=n,s,g={},u=r.is('html,body');switch(typeof f){case'number':case'string':if(/^([+-]=)?\d+(\.\d+)?(px|%)?$/.test(f)){f=p(f);break}f=d(f,this);case'object':if(f.is||f.style)s=(f=d(f)).offset()}d.each(b.axis.split(''),function(a,i){var e=i=='x'?'Left':'Top',h=e.toLowerCase(),c='scroll'+e,l=q[c],m=k.max(q,i);if(s){g[c]=s[h]+(u?0:l-r.offset()[h]);if(b.margin){g[c]-=parseInt(f.css('margin'+e))||0;g[c]-=parseInt(f.css('border'+e+'Width'))||0}g[c]+=b.offset[h]||0;if(b.over[h])g[c]+=f[i=='x'?'width':'height']()*b.over[h]}else{var o=f[h];g[c]=o.slice&&o.slice(-1)=='%'?parseFloat(o)/100*m:o}if(/^\d+$/.test(g[c]))g[c]=g[c]<=0?0:Math.min(g[c],m);if(!a&&b.queue){if(l!=g[c])t(b.onAfterFirst);delete g[c]}});t(b.onAfter);function t(a){r.animate(g,j,b.easing,a&&function(){a.call(this,n,b)})}}).end()};k.max=function(a,i){var e=i=='x'?'Width':'Height',h='scroll'+e;if(!d(a).is('html,body'))return a[h]-d(a)[e.toLowerCase()]();var c='client'+e,l=a.ownerDocument.documentElement,m=a.ownerDocument.body;return Math.max(l[h],m[h])-Math.min(l[c],m[c])};function p(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);

/* This TipTip jQuery plug-in is dual licensed under the MIT and GPL licenses:
 *   http://www.opensource.org/licenses/mit-license.php
 *   http://www.gnu.org/licenses/gpl.html
 */
(function($){$.fn.tipTip=function(options){var defaults={activation:"hover",keepAlive:false,maxWidth:"200px",edgeOffset:3,defaultPosition:"bottom",delay:400,fadeIn:200,fadeOut:200,attribute:"title",content:false,enter:function(){},exit:function(){}};var opts=$.extend(defaults,options);if($("#tiptip_holder").length<=0){var tiptip_holder=$('<div id="tiptip_holder" style="max-width:'+opts.maxWidth+';"></div>');var tiptip_content=$('<div id="tiptip_content"></div>');var tiptip_arrow=$('<div id="tiptip_arrow"></div>');$("body").append(tiptip_holder.html(tiptip_content).prepend(tiptip_arrow.html('<div id="tiptip_arrow_inner"></div>')))}else{var tiptip_holder=$("#tiptip_holder");var tiptip_content=$("#tiptip_content");var tiptip_arrow=$("#tiptip_arrow")}return this.each(function(){var org_elem=$(this);if(opts.content){var org_title=opts.content}else{var org_title=org_elem.attr(opts.attribute)}if(org_title!=""){if(!opts.content){org_elem.removeAttr(opts.attribute)}var timeout=false;if(opts.activation=="hover"){org_elem.hover(function(){active_tiptip()},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}else if(opts.activation=="focus"){org_elem.focus(function(){active_tiptip()}).blur(function(){deactive_tiptip()})}else if(opts.activation=="click"){org_elem.click(function(){active_tiptip();return false}).hover(function(){},function(){if(!opts.keepAlive){deactive_tiptip()}});if(opts.keepAlive){tiptip_holder.hover(function(){},function(){deactive_tiptip()})}}function active_tiptip(){opts.enter.call(this);tiptip_content.html(org_title);tiptip_holder.hide().removeAttr("class").css("margin","0");tiptip_arrow.removeAttr("style");var top=parseInt(org_elem.offset()['top']);var left=parseInt(org_elem.offset()['left']);var org_width=parseInt(org_elem.outerWidth());var org_height=parseInt(org_elem.outerHeight());var tip_w=tiptip_holder.outerWidth();var tip_h=tiptip_holder.outerHeight();var w_compare=Math.round((org_width-tip_w)/2);var h_compare=Math.round((org_height-tip_h)/2);var marg_left=Math.round(left+w_compare);var marg_top=Math.round(top+org_height+opts.edgeOffset);var t_class="";var arrow_top="";var arrow_left=Math.round(tip_w-12)/2;if(opts.defaultPosition=="bottom"){t_class="_bottom"}else if(opts.defaultPosition=="top"){t_class="_top"}else if(opts.defaultPosition=="left"){t_class="_left"}else if(opts.defaultPosition=="right"){t_class="_right"}var right_compare=(w_compare+left)<parseInt($(window).scrollLeft());var left_compare=(tip_w+left)>parseInt($(window).width());if((right_compare&&w_compare<0)||(t_class=="_right"&&!left_compare)||(t_class=="_left"&&left<(tip_w+opts.edgeOffset+5))){t_class="_right";arrow_top=Math.round(tip_h-13)/2;arrow_left=-12;marg_left=Math.round(left+org_width+opts.edgeOffset);marg_top=Math.round(top+h_compare)}else if((left_compare&&w_compare<0)||(t_class=="_left"&&!right_compare)){t_class="_left";arrow_top=Math.round(tip_h-13)/2;arrow_left=Math.round(tip_w);marg_left=Math.round(left-(tip_w+opts.edgeOffset+5));marg_top=Math.round(top+h_compare)}var top_compare=(top+org_height+opts.edgeOffset+tip_h+8)>parseInt($(window).height()+$(window).scrollTop());var bottom_compare=((top+org_height)-(opts.edgeOffset+tip_h+8))<0;if(top_compare||(t_class=="_bottom"&&top_compare)||(t_class=="_top"&&!bottom_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_top"}else{t_class=t_class+"_top"}arrow_top=tip_h;marg_top=Math.round(top-(tip_h+5+opts.edgeOffset))}else if(bottom_compare|(t_class=="_top"&&bottom_compare)||(t_class=="_bottom"&&!top_compare)){if(t_class=="_top"||t_class=="_bottom"){t_class="_bottom"}else{t_class=t_class+"_bottom"}arrow_top=-12;marg_top=Math.round(top+org_height+opts.edgeOffset)}if(t_class=="_right_top"||t_class=="_left_top"){marg_top=marg_top+5}else if(t_class=="_right_bottom"||t_class=="_left_bottom"){marg_top=marg_top-5}if(t_class=="_left_top"||t_class=="_left_bottom"){marg_left=marg_left+5}tiptip_arrow.css({"margin-left":arrow_left+"px","margin-top":arrow_top+"px"});tiptip_holder.css({"margin-left":marg_left+"px","margin-top":marg_top+"px"}).attr("class","tip"+t_class);if(timeout){clearTimeout(timeout)}timeout=setTimeout(function(){tiptip_holder.stop(true,true).fadeIn(opts.fadeIn)},opts.delay)}function deactive_tiptip(){opts.exit.call(this);if(timeout){clearTimeout(timeout)}tiptip_holder.fadeOut(opts.fadeOut)}}})}})(jQuery);

/*
 * jQuery autoResize
 * @copyright http://www.sitepoint.com/build-auto-expanding-textarea-3/
 * @version 1.04
 */
//(function(a){a.fn.TextAreaExpander=function(b,c){function e(a){a=a.target||a;var b=a.value.length,c=a.offsetWidth;if(b!=a.valLength||c!=a.boxWidth){if(d&&(b<a.valLength||c!=a.boxWidth))a.style.height="0px";var e=Math.max(a.expandMin,Math.min(a.scrollHeight,a.expandMax));a.style.overflow=a.scrollHeight>e?"auto":"hidden";a.style.height=e+"px";a.valLength=b;a.boxWidth=c}return true}var d=!(a.browser.msie||a.browser.opera);this.each(function(){if(this.nodeName.toLowerCase()!="textarea")return;var d=this.className.match(/expand(\d+)\-*(\d+)*/i);this.expandMin=b||(d?parseInt("0"+d[1],10):0);this.expandMax=c||(d?parseInt("0"+d[2],10):99999);e(this);if(!this.Initialized){this.Initialized=true;a(this).css("padding-top",0).css("padding-bottom",0);a(this).bind("keyup",e)}});return this}})(jQuery);jQuery(document).ready(function(){jQuery("textarea[class*=expand]").TextAreaExpander()})

/*
* jQuery.fn.autoResize 1.14
* --
* https://github.com/padolsey/jQuery.fn.autoResize
*/
(function(d){var b="ar"+ +new Date,e=c.defaults={onResize:function(){},onBeforeResize:function(){return 123},onAfterResize:function(){return 555},animate:{duration:200,complete:function(){}},extraSpace:50,minHeight:"original",maxHeight:500,minWidth:"original",maxWidth:500};c.cloneCSSProperties=["lineHeight","textDecoration","letterSpacing","fontSize","fontFamily","fontStyle","fontWeight","textTransform","textAlign","direction","wordSpacing","fontSizeAdjust","paddingTop","paddingLeft","paddingBottom","paddingRight","width"];c.cloneCSSValues={position:"absolute",top:-9999,left:-9999,opacity:0,overflow:"hidden"};c.resizableFilterSelector=["textarea:not(textarea."+b+")","input:not(input[type])","input[type=text]","input[type=password]","input[type=email]","input[type=url]"].join(",");c.AutoResizer=a;d.fn.autoResize=c;function c(f){this.filter(c.resizableFilterSelector).each(function(){new a(d(this),f)});return this}function a(g,f){if(g.data("AutoResizer")){g.data("AutoResizer").destroy()}f=this.config=d.extend({},c.defaults,f);this.el=g;this.nodeName=g[0].nodeName.toLowerCase();this.originalHeight=g.height();this.previousScrollTop=null;this.value=g.val();if(f.maxWidth==="original"){f.maxWidth=g.width()}if(f.minWidth==="original"){f.minWidth=g.width()}if(f.maxHeight==="original"){f.maxHeight=g.height()}if(f.minHeight==="original"){f.minHeight=g.height()}if(this.nodeName==="textarea"){g.css({resize:"none",overflowY:"hidden"})}g.data("AutoResizer",this);f.animate.complete=(function(h){return function(){f.onAfterResize.call(g);return h.apply(this,arguments)}}(f.animate.complete));this.bind()}a.prototype={bind:function(){var f=d.proxy(function(){this.check();return true},this);this.unbind();this.el.bind("keyup.autoResize",f).bind("change.autoResize",f).bind("paste.autoResize",function(){setTimeout(function(){f()},0)});if(!this.el.is(":hidden")){this.check(null,true)}},unbind:function(){this.el.unbind(".autoResize")},createClone:function(){var f=this.el,g=this.nodeName==="textarea"?f.clone():d("<span/>");this.clone=g;d.each(c.cloneCSSProperties,function(h,j){g[0].style[j]=f.css(j)});g.removeAttr("name").removeAttr("id").addClass(b).attr("tabIndex",-1).css(c.cloneCSSValues);if(this.nodeName==="textarea"){g.height("auto")}else{g.width("auto").css({whiteSpace:"nowrap"})}},check:function(l,j){if(!this.clone){this.createClone();this.injectClone()}var i=this.config,m=this.clone,h=this.el,n=h.val();if(n===this.prevValue){return true}this.prevValue=n;if(this.nodeName==="input"){m.text(n);var o=m.width(),k=(o+i.extraSpace)>=i.minWidth?o+i.extraSpace:i.minWidth,g=h.width();k=Math.min(k,i.maxWidth);if((k<g&&k>=i.minWidth)||(k>=i.minWidth&&k<=i.maxWidth)){i.onBeforeResize.call(h);i.onResize.call(h);h.scrollLeft(0);if(i.animate&&!j){h.stop(1,1).animate({width:k},i.animate)}else{h.width(k);i.onAfterResize.call(h)}}return}m.width(h.width()).height(0).val(n).scrollTop(10000);var f=m[0].scrollTop;if(this.previousScrollTop===f){return}this.previousScrollTop=f;if(f+i.extraSpace>=i.maxHeight){h.css("overflowY","");f=i.maxHeight;j=true}else{if(f<=i.minHeight){f=i.minHeight}else{h.css("overflowY","hidden");f+=i.extraSpace}}i.onBeforeResize.call(h);i.onResize.call(h);if(i.animate&&!j){h.stop(1,1).animate({height:f},i.animate)}else{h.height(f);i.onAfterResize.call(h)}},destroy:function(){this.unbind();this.el.removeData("AutoResizer");this.clone.remove();delete this.el;delete this.clone},injectClone:function(){(c.cloneContainer||(c.cloneContainer=d("<arclones/>").appendTo("body"))).append(this.clone)}}})(jQuery);

/* Smiles ------------------------------------------------------*/
// replace smile with code
function smile(what){
    /*document.getElementById('add_msg').text.focus();
    document.getElementById('add_msg').text.value = document.getElementById('add_msg').text.value + what;*/    
    $("#text").insertAtCaret(what);
}

$(document).ready(function(){
    // insert text at current cursor position
    jQuery.fn.extend({
    insertAtCaret: function(myValue){
      return this.each(function(i) {
        if (document.selection) {
          //For browsers like Internet Explorer
          this.focus();
          sel = document.selection.createRange();
          sel.text = myValue;
          this.focus();
        }
        else if (this.selectionStart || this.selectionStart == '0') {
          //For browsers like Firefox and Webkit based
          var startPos = this.selectionStart;
          var endPos = this.selectionEnd;
          var scrollTop = this.scrollTop;
          this.value = this.value.substring(0, startPos)+myValue+this.value.substring(endPos,this.value.length);
          this.focus();
          this.selectionStart = startPos + myValue.length;
          this.selectionEnd = startPos + myValue.length;
          this.scrollTop = scrollTop;
        } else {
          this.value += myValue;
          this.focus();
        }
      })
    }
});


});
// Serach input focus
$(document).ready(function(){    
    if (window.location.pathname == '/') {
        $("#input").focus();
    } else if (window.location.pathname == '/uzivatele/strana-1') {
        $("#input_user").focus();
    }
    $("#input").attr("placeholder", searchInputTextG);
});

/* Admin jquery function */

// Remove row from table
$(document).ready(function(){    
    $(".del_row").click(function(event){
        $.get($(this).attr('href'));
        $(this).parent().parent().fadeOut("slow", function() {
            $(this).remove();
        });
        event.preventDefault();
    });
});

// Remove row from table with prompt
$(document).ready(function(){
    $(".del_row_prompt").click(function(event){
        var x = confirm('!!! POZOR opravdu to chceš smazat !!?');
        if (x == true) {
            $.get($(this).attr('href'));
            $(this).parent().parent().fadeOut("slow", function() {
                $(this).remove();
            });
        }
        event.preventDefault();
    });
});

// Toggle admin menu
$(document).ready(function(){
    $(".toggle_admin_menu").click(function(event) {
        $("#admin_menu").slideToggle(600);        

        if (readCookie('hideAdminMenu')) {
            eraseCookie('hideAdminMenu');
            $(this).text('-');
            $("div#approve_menu").slideDown(600);
        } else {
            createCookie('hideAdminMenu', 1, 100);
            $(this).text('+');
            $("div#approve_menu").slideUp(600);
        }
        event.preventDefault();
    });

});

// Fanclubs selector
$(document).ready(function(){
    $("select#fanclubs").change(function(event) {       
        window.location = $(this).attr('value');
    });
});


// autocomplete search
$(document).ready(function() {

    // serach artists and songs
    $('input#input').autocomplete({
        delay: 5,
        source: function(request, response) {

            var q = $('input#input').attr("value");
            
            $.ajax({
                url: "http://search.karaoketexty.cz/index.php",
                dataType: "jsonp",
                data: {
                    q: q,
                    lang: langG
                },
                success: function(data) {
                    response(data);
                }
            })
        },
        select: function(event, ui) {
            var hostname = top.location.host;
            var url = "http://" + hostname + "/search?q=";
            var rnd = Math.random().toString(36).substring(5);
            window.location.replace(url + ui.item.value + "&t=at&from=sug&type=" + ui.item.type + "&id=" + ui.item.id + "&sid=" + rnd);
        }
    });   


    $('input.nick_autocomplete').autocomplete({
        delay: 5,
        source: function(request, response) {

            var q = $('input.nick_autocomplete').attr("value");

            $.ajax({
                url: "http://search.karaoketexty.cz/index.php",
                dataType: "jsonp",
                data: {
                    q: q,
                    type: 'users',
                    lang: langG
                },
                success: function(data) {
                    response(data);
                }
            })
        }        
    });


    $("#search_type").change(function() {
        var type = $(this).attr("value");
        if (type == 'f') {
            $('input#input').autocomplete("disable");
        } else {
            $('input#input').autocomplete("enable");
        }
    });

});
 
// coockie functions
function createCookie(name,value,days) {
    var expires;
    if (days) {
            var date = new Date();
            date.setTime(date.getTime()+(days*24*60*60*1000));
            expires = "; expires="+date.toGMTString();
    } else {
        expires = "";
    }
    document.cookie = name+"="+value+expires+"; path=/";
}

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);
}

/* Messages -----*/
$(document).ready(function() {

    $(".del_message").click(function(event) {
        $.get($(this).attr('href'));
        $(this).parent().parent().css("background", "mistyrose");
        $(this).parent().parent().fadeOut(1000, function() {
            $(this).remove();
        });
        event.preventDefault();
    });

});

/* Others ---------------------------------------------*/

$(document).ready(function() {
    // External links counter
    $(".external_link").click(function(event) {
        $.get('http://www.karaoketexty.cz/admin/stats/updateExternalLinksStats/title/superhry.cz');
    });

    // Search User Advanced - age check
    $('#SubmitSearchAdvanced').click(function(event) {
        var from = $('select#from option:selected').val();
        var to = $('select#to option:selected').val();
                
        if (parseInt(from) > parseInt(to)) {
            alert("Věk 'od' musí být menší než věk 'do'");
            event.preventDefault();
        }
    });

    // Autoresize textareas
    //$('textarea.autoresize').TextAreaExpander(400, 3000);
    $('textarea.autoresize').autoResize({
        maxHeight: 2000,
        extraSpace: 4,
        animate: false
    });
        
});



/* Playlist --------------------------------------------*/
function stateChange(state) {
    //alert(seekedG);
    if (state == 0) {
        //update plays
        $.get('/playlist/updatePlays/pid/' + pidG + '/seeked/' + seekedG);
        
        var nextItem = getNextItem(currentItemG.attr('order'));
        loadVideoAndText(currentItemG, nextItem);
        var offset = nextItem.attr('order') * 39;
        if (offset > 330) {
            $('#playlist').scrollTo(offset + 'px');
        } else {
            $('#playlist').scrollTo('0px');
        }       

    } else if (state == 2) {
        var diff = Math.abs(ytplayer.getDuration() - ytplayer.getCurrentTime());
        //alert(diff);
        if (diff > 10) seekedG = true;
    }    
}

// return next item in playlist
function getNextItem(current) {
    var nextItem = null;

    if (!randomG) {
        nextItem = currentItemG.next();
        // after last element jump to start
        /*if (nextItem.size() == 0) {
            nextItem = $('#playlist div').first();
        }*/
    } else {        
        var size = $('#playlist div.not_played').size();
        //all songs is played
        if (size == 0) {
            $('#playlist div').each(function() {
                $(this).addClass('not_played');
            });
            return null;
        }
        var pos = Math.floor(Math.random() * size);
        while (pos == current) pos = Math.floor(Math.random() * size);
        var items = $('#playlist div.not_played');
        nextItem = items.slice(pos, pos + 1);        

        /*var size = $('#playlist div').size();
        var pos = Math.floor(Math.random() * size);
        while (pos == current) pos = Math.floor(Math.random() * size);
        var items = $('#playlist div');
        nextItem = items.slice(pos, pos + 1);*/
    }

    return nextItem;
}

function loadVideoAndText(previousItem, item) {
    currentItemG = item;

    if (previousItem) previousItem.removeClass('current');

    currentItemG.addClass('current');
    var id = item.find('a').attr('id');
    var sid = item.find('a').attr('sid');    

    ytplayer.loadVideoById(id);
    
    $('.content').fadeOut('fast', function() {
        $.get('/ajax/song/lyricsBySid.php?sid=' + sid, function(data) {
            $('.content').html(data);
            $('#original').show();
            $('.content').fadeIn();
            translateG = false;
            
            var title = new String($('#right_part .content .song').html());
            var artist = new String($('#right_part .content .artist').html());

            title = title.replace("&amp;",'');
           
            document.title = title + ' - ' + artist;
        });
    });

    currentItemG.removeClass('not_played');
    seekedG = false;
}

function loadVideo(item) {
    var id = item.find('a').attr('id');
    if (firstRunG) {
        defineYtplayer(id);
    } else {
        ytplayer.loadVideoById(id);
    }
    /*$('#playlist div.item_edit').removeClass('current');
    item.addClass('current');*/
}

function defineYtplayer(id) {
    swfobject.embedSWF("http://www.youtube.com/e/" + id + "?enablejsapi=1&playerapiid=ytplayer&rel=0&showinfo=0&showsearch=0&autohide=1&fs=1&wmode=transparent",
           "ytapiplayer", "425", "356", "8", null, null, params, atts);
    firstRunG = false;
    currentIdG = id;
}

function onYouTubePlayerReady() {
    ytplayer = document.getElementById("myytplayer");
    ytplayer.addEventListener("onStateChange", "stateChange");    
    if (currentItemG) loadVideoAndText(null, currentItemG);
    else if (emptyPlaylistG == false) {
        ytplayer.pauseVideo();
    } else if (currentIdG) ytplayer.loadVideoById(currentIdG);    
}

$(document).ready(function() {

    $('#playlist div.item').live('click', function(event) {
        var item = $(this).closest('div').closest('div');
        loadVideoAndText(currentItemG, item);        
        event.preventDefault();
    });    

    $('#playlist div.item, #playlist div.item_edit').live('mouseover', function() {
        if (!$(this).hasClass('current')) $(this).addClass('hover');
        $(this).find('div.remove').show();
        $(this).find('div.move').show();
    });

    $('#playlist div.item, #playlist div.item_edit').live('mouseout' , function() {
        $(this).removeClass('hover');
        $(this).find('div.remove').hide();
        $(this).find('div.move').hide();
    });

    $('#playlist div.remove').live('mouseover', function() {
        $(this).css('background-image', 'url("/img/remove_small.png")');
    });

    $('#playlist div.remove').live('mouseout', function() {
        $(this).css('background-image', 'url("/img/remove_small_gray.png")');
    });

    $('.vote_like').click(function(event) {
        var counter = null;
        if (signedG == 'false') {
            alert(strHaveToSignUp);
        } else {
            if ((likeG == 0) || (likeG == 2)) {
                $.get('/playlist/likeDislike/pid/' + pidG + '/like/like');
                counter = parseInt($('.like_counter').html());
                counter++;
                $('.like_counter').html("" + counter);
                $(this).addClass('up_highlight');
                $('.vote_dislike').removeClass('down_highlight');
                $('.vote_dislike').css('cursor', 'pointer');
                if (likeG == 2) {
                    counter = parseInt($('.dislike_counter').html());
                    counter--;
                    $('.dislike_counter').html("" + counter);
                }
                likeG = 1;
            }
        }
        event.preventDefault();
    });

    $('.vote_dislike').click(function(event) {
        var counter = null;
        if (signedG == 'false') {
            alert(strHaveToSignUp);
        } else {
            if ((likeG == 0) || (likeG == 1)) {
                $.get('/playlist/likeDislike/pid/' + pidG + '/like/dislike');
                counter = parseInt($('.dislike_counter').html());
                counter++;
                $('.dislike_counter').html("" + counter);
                $(this).addClass('down_highlight');
                $('.vote_like').removeClass('up_highlight');
                $('.vote_like').css('cursor', 'pointer');
                if (likeG == 1) {
                    counter = parseInt($('.like_counter').html());
                    counter--;
                    $('.like_counter').html("" + counter);
                }
                likeG = 2;
            }
        }
        event.preventDefault();
    });

    $('.thumb_up').mouseover(function() {
        if ((likeG == 0) || (likeG == 2)) {
            $(this).addClass('up_highlight');
        } else {
            $(this).css('cursor', 'default');
        }
    });

    $('.thumb_up').mouseout(function() {
        if ((likeG == 0) || (likeG == 2)) {
            $(this).removeClass('up_highlight');
        }
    });

    $('.thumb_down').mouseover(function() {
        if ((likeG == 0) || (likeG == 1)) {
            $(this).addClass('down_highlight');
        } else {
            $(this).css('cursor', 'default');
        }
    });

    $('.thumb_down').mouseout(function() {
        if ((likeG == 0) || (likeG == 1)) {
            $(this).removeClass('down_highlight');
        }
    });

    $('.random').click(function() {
        if (!randomG) {
            randomG = true;
            $('.random').attr('title', strRandomOff);
            $('.random img').attr('src', '/img/random_black.png');
        } else {
            randomG = false;
            $('.random').attr('title', strRandomOn);
            $('.random img').attr('src', '/img/random.png');
        }
    });

    $('#switch').live('click', function(event) {
        if (!translateG) {
            translateG = true;
            $("#original").hide();
            $("#translate").fadeIn();
            $(this).attr('title', strShowOrig);
        } else {
            translateG = false;
            $("#translate").hide();
            $("#original").fadeIn();
            $(this).attr('title', strShowTranslate);
        }
        event.preventDefault();
    })

    $("#switch").tipTip();
});

/* Create Playlist --------------------------------------------*/
$(document).ready(function() {    

    $('#searchSong').keyup(function(event) {        
        var q = $(this).attr('value');
        
        $("#searched_part .ajax_loading").show();

        $.ajax({
            url: "http://search.karaoketexty.cz/index.php",
            dataType: "jsonp",
            data: {
                q: q,
                type: 'videos',
                lang: langG
            },
            success: function(data) {                
                //response(data);

                $("#searched").show();
                $('#searched').html(data);
                $("#searched_part .ajax_loading").hide();

                //hide added videos
                var row = null;
                $('#playlist div.item_edit').find('a').each(function() {
                    row = $('#searched').find('div.add_item[sid=' + $(this).attr('sid') + ']');
                    row.hide();
                    row.parent().parent().find('div.song').addClass('added');
                });
            }
        });
    });

    $("#searched div.song").live('click', function(event) {
        event.preventDefault();
    });

    $("#searched div.add_item").live('click', function(event) {
        $('#playlist').prepend(
            '<div class="clear item_edit"><div class="content">\n\
            <img class="video" alt="video" src="http://i.ytimg.com/vi/' + $(this).attr('videoId') + '/1.jpg">\n\
            <a href="#" sid="' + $(this).attr('sid') + '" id="' + $(this).attr('videoId') + '">' + $(this).attr('nazev') + '</a>\n\
            ' + $(this).attr('artist') + '</div>\n\
            <div title="' + removeVideoMsg + '" class="remove"></div></div>'
        );
        if (firstRunG) {
            defineYtplayer($(this).attr('videoId'));
        }
        $.get('/playlist/addVideo/pid/' + pidG + '/id/' + $(this).attr('sid'));
        
        //$('#playlist').scrollTo(($("#playlist div.item_edit").length * 26) + 'px');
        if ($("#playlist div.item_edit").length > 0) {
            $("#playlist_done").show();
            $("#playlist_done_msg").show();
        }
        $(this).hide();
        $(this).parent().parent().find('div.song').addClass('added');
        event.preventDefault();
    });

    $("#searched div.song a").live('click', function(event) {
        var id = $(this).parent().siblings('div').find('div').attr('videoId');
        if (firstRunG) {
            defineYtplayer(id);
        } else {
            ytplayer.loadVideoById(id);
        }
        event.preventDefault();
    });

    $('#searched div.row').live('mouseover', function() {        
        if (!$(this).find('div.song').hasClass('added')) {
            $(this).find('div.add_item').show();            
        }
        $(this).addClass('highlight');
    });

    $('#searched div.row').live('mouseout', function() {
        $(this).find('div.add_item').hide();
        $(this).removeClass('highlight');
    });

    $('div.item_edit div.remove').live('click', function(event) {
        var sid = $(this).siblings().find('a').attr('sid');        
        $(this).parent().fadeOut(400, function() {
            $(this).remove();
            if ($("#playlist div.item_edit").length == 0) {
                $("#playlist_done").hide();
                $("#playlist_done_msg").hide();
            }
        });                
        $.get('/playlist/removeVideo/pid/' + pidG + '/id/' + sid);
        $('#searched').find('div[sid=' + sid + ']').parent().parent().find('div.song').removeClass('added');
    });

    $('#playlist div.item_edit div.content').live('click', function(event) {
        var item = $(this).closest('div').closest('div');
        loadVideo(item);
        event.preventDefault();
    });        

    /*$('#playlist_info div').live('mouseover', function() {
        $(this).find('span.edit').show();
    });

    $('#playlist_info div').live('mouseout', function() {
        $(this).find('span.edit').hide();
    });

    $('#edit_title').live('click', function(event) {
        event.preventDefault();
        var p = $(this).parent();
        $(this).remove();
        var title = p.html();        
        p.html('<input type="text" value="' + title + '" /><input type="submit" value="OK" />');
    });*/

});

/* Search stats --------------------------------------------*/
$(document).ready(function() {
    
    $("#search ul.artist li a").click(function(event) {
        url = $(this).attr('href');
        $.get('/ajax/search/searchClicks.php?type=artist&searchSid=' + searchSid, function(data) {
            //alert('/ajax/search/searchClicks.php?type=artist&searchSid=' + searchSid); 
            window.location.replace(url);
        });
        event.preventDefault();
    });

    $("#search ul.title li a").click(function(event) {
        url = $(this).attr('href');
        $.get('/ajax/search/searchClicks.php?type=title&searchSid=' + searchSid, function(data) {
            //alert('/ajax/search/searchClicks.php?type=title&searchSid=' + searchSid);
            window.location.replace(url);
        });
        event.preventDefault();
    });

    $("#fulltextSearch ul li a").click(function() {
        $.get('/ajax/search/searchClicks.php?type=lyrics');
    });
});

/* Add to playlist icon ------------------------------------*/
$(document).ready(function() {

    $("a#add_to_playlist").show();

    $("#add_to_playlist").click(function(event) {
        $("#add_to_playlist_div").toggle();
        event.preventDefault();
    });

  /*  $("#show_lyrics_icon, #add_to_playlist_div").mouseout(function() {
        $("#add_to_playlist_div").hide();
    });
    
    $("#show_lyrics_icon").mouseover(function() {
        $("#add_to_playlist_div").show();
        $("#add_to_playlist_ok").hide();
        $("#add_to_playlist_err").hide();
    });*/

    $("#add_to_playlist_ok a, #add_to_playlist_err a").click(function(event) {
        $(this).parent().parent().hide();
        event.preventDefault();
    });
   
    $("#add_to_playlist_div img").click(function(event) {
        $(this).parent().parent().parent().hide();
        event.preventDefault();
    });

    $("#add_to_playlist_div a.add_song_to_playlist").click(function(event) {
        var url = $(this).attr('href');
        $.get(url, function(data) {
            $("#add_to_playlist_div").hide();            
            if (data == 1) {
                $("#add_to_playlist_ok").show().delay(2000).fadeOut();
            } else {
                $("#add_to_playlist_err").show().delay(2000).fadeOut();
            }
        });               

        event.preventDefault();
    });

});

/* Check unread messages ------------------------------------*/
$(document).ready(function() {
    
    var titleOrig = document.title;
    var logged = false;

    if ($("#loggedUser").length > 0) {
        logged = true;
    }          

    window.getNewMessages = function(callbackFunc, timing) {
        var variableInterval = {
            interval: timing,
            callback: callbackFunc,
            stopped: false,
            runLoop: function() {
                if (variableInterval.stopped) return;
                var result = variableInterval.callback.call(variableInterval);
                if (typeof result == 'number'){
                    if (result === 0) return;
                    variableInterval.interval = result;
                }
                variableInterval.loop();
            },
            stop: function() {
                this.stopped = true;
                window.clearTimeout(this.timeout);
            },
            start: function() {
                this.stopped = false;
                return this.loop();
            },
            loop: function() {
                this.timeout = window.setTimeout(this.runLoop, this.interval);
                return this;
            }
        };

        return variableInterval.start();
    };

    if (logged) {
        var vi = getNewMessages(function() {

            // this is the variableInterval - so we can change/get the interval here:
            var interval = this.interval;

            // print it for the hell of it
            //console.log(interval);

            $.get('/ajax/message/getUnreadMessagesCount.php', function(data) {
                var msgCount = $("#unreadMsessagesCount").html();
                var newMsgCount = data;

                if (newMsgCount == parseInt(newMsgCount)) {
                    if (msgCount != newMsgCount) {
                        if (newMsgCount == 0) {
                            $("#unreadMsgWrapper").hide();
                            document.title = titleOrig;
                        } else {
                            $("#unreadMsgWrapper").show();
                            $("#unreadMsessagesCount").hide().html(newMsgCount).fadeIn('slow');

                            document.title = '(' + newMsgCount + ') ' + titleOrig;
                        }
                    }
                }
            });

            lastCheck = Math.round(new Date().getTime() / 1000);

            // we could return a new interval after doing something
            return interval + 3000;

        }, 3000);
    }

    $(window).focus(function () {
        if (logged) {
            // don't read new message count in short period than 15 seconds
            setTimeout(function() {
                vi.interval = 3000;
                vi.start();
            }, 3000);
        }
        //console.log('focus');
    })

    $(window).blur(function () {
        if (logged) {
            vi.stop();
        }
        //console.log('blur');
    })

}); 



/* Playlists page---------------------------------*/
$(document).ready(function() {

    $('#recomended_playlist_wrapper .recomended_playlist').mouseout(function() {
        $(this).find('.play_icon').hide();
        $(this).find('a.title').removeClass('green');
    });

    $('#recomended_playlist_wrapper .recomended_playlist').mouseover(function() {
        $(this).find('.play_icon').show();
        $(this).find('a.title').addClass('green');
    });
});
