/**
** A JS function for dumping JS objects data, similar to PHP's print_r
**/
function e(arr, return_text, level, objs_dumped)
{
    var dumped_text, level_padding, j, k, item, value, already_dumped;
    
    if (return_text === undefined) {
        return_text = false;
    }
    dumped_text = "";
    if (!level) {
        level = 0;
    }
    if (objs_dumped === undefined) {
        objs_dumped = [];
    }
    
    //The padding given at the beginning of the line.
    level_padding = "";
    for (j = 0; j < level + 1;) {
        level_padding += "    ";
        j += 1;
    }
    
    if (typeof(arr) === 'object') { //Array/Hashes/Objects 
        for (item in arr) {
            // if (arr.hasOwnProperty(item)) {
                try {
                    value = arr[item];
                    if (value === null) {
                        dumped_text += level_padding + "'" + item + "' => null\n";
                    }
                    else {
                        if (typeof(value) === 'object') { //If it is an array,
                            dumped_text += level_padding + "'" + item + "' ...\n";
                            // Recursion protection
                            already_dumped = false;
                            for (k = 0; k < objs_dumped.length;) {
                                if (value === objs_dumped[k]) {
                                    already_dumped = true;
                                    dumped_text += 'recursion! (already dumped somewhere above)\n';
                                    break;
                                }
                                k += 1;
                            }
                            if (already_dumped === false) {
                                objs_dumped[objs_dumped.length] = value;
                                dumped_text += e(value, true, level + 1, objs_dumped);
                            }
                        
                        } else {
                            dumped_text += level_padding + "'" + item + "' => \"" + value + "\"\n";
                        }
                    }
                } catch (err) {}
            // }
        }
    } else { //Stings/Chars/Numbers etc.
        dumped_text = "===>" + arr + "<===(" + typeof(arr) + ")";
    }
    
    if (return_text) {
        return dumped_text;
    }
    else {
        alert(dumped_text);
    }
}

String.prototype.trim = function()
{
	return this.replace(/^\s+|\s+$/g,"");
};

String.prototype.ltrim = function()
{
	return this.replace(/^\s+/g,"");
};

String.prototype.rtrim = function()
{
	return this.replace(/\s+$/g,"");
};


function urlChangeParam(param, value, url)
{
    var i, url, urlPrefix, paramsSegments, params, paramsPos, paramsStr, paramsArr;
    
    if (url === undefined) {
        url = document.location.href;
    }
    
    // If there is an anchor in this url - we must move it to the back
    anchorStr = '';
    anchorStrPos = url.indexOf('/#');
    if (anchorStrPos >= 0)
    {
        anchorStr = url.slice(anchorStrPos);
        url = url.slice(0, anchorStrPos);
    }
    
    paramsPos = url.indexOf(',');
    if (paramsPos < 0)
        paramsPos = url.length;
    urlPrefix = url.substr(0, paramsPos);
    paramsStr = url.substr(paramsPos);
    paramsStr = paramsStr.replace(/^\//, '').replace(/\/$/, '');
    
    paramsSegments = paramsStr.split('/');
    params  = {};
    if (paramsSegments.length > 1) {
        for (i = 0; i < paramsSegments.length;)
        {
            params[paramsSegments[i]] = paramsSegments[i + 1];
            i += 2;
        }
    }
    
    if (value !== false)
        params[param]   = value;
    else
        delete params[param];
    
    paramsArr       = [];
    jQuery.each(params, function (key, value)
    {
        paramsArr.push(key + '.' + value);
    });
    paramsStr = paramsArr.join(',');
    
    return urlPrefix + (paramsStr ? ',' + paramsStr : '') + anchorStr;
}

function urlChangeAnchor(anchor, url)
{
    if (url === undefined)
        url = document.location.href;
    var anchorStrPos = url.indexOf('#');
    if (anchorStrPos >= 0)
        return url.slice(0, anchorStrPos + 1) + anchor;
    else
        return url + '#' + anchor;
}

function urlGetAnchor(url)
{
    if (url === undefined)
        url = document.location.href;
    var anchorStrPos = url.indexOf('#');
    if (anchorStrPos >= 0)
        return url.slice(anchorStrPos + 1);
    
    return false;
}

function setSelRange(inputEl, selStart, selEnd)
{ 
	if (inputEl.setSelectionRange)
	{ 
		inputEl.focus(); 
		inputEl.setSelectionRange(selStart, selEnd); 
	} else if (inputEl.createTextRange)
	{ 
		var range = inputEl.createTextRange(); 
		range.collapse(true); 
		range.moveEnd('character', selEnd); 
		range.moveStart('character', selStart); 
		range.select(); 
	}
}

/*
 * jQuery :focus selector (not implemented in jQuery < 1.6)
 * From: http://stackoverflow.com/questions/967096/using-jquery-to-test-if-an-input-has-focus
 */
(function ( $ ) {
    var filters = $.expr[":"];
    if ( !filters.focus ) { 
        filters.focus = function( elem ) {
           return elem === document.activeElement && ( elem.type || elem.href );
        };
    }
})( jQuery );


// Facebook login button
$.extend(true, {
    "app": {
        "fbLogin": function (args)
        {
            // fbLogin should only run, once page has been loaded (it is possible for user to click it before then (i think...))
            $(function ()
            {
                FB.api('/me', function(user)
                {
                    if (user && ! user.error)
                        $.post($.app.site_base_href + 'external/ajax/', {
                            "fn": 'fbLoginUser'
                          , "user": user
                        }, function (json)
                        {
                            if (json.success)
                                document.location.reload(true);
                        }, 'json');
                });
            });
        }
    }
});

//////////////////////////////////// xml_decode() ////////////////////////////////////////
//See http://www.openjs.com/scripts/xml_parser/

//Process the xml data
function xml_decode(xmlDoc, parent_count)
{
    var not_whitespace = new RegExp(/[^\s]/);
    var arr = new Object;
    var parent = "";
    parent_count = parent_count || new Object;

    if (typeof(xmlDoc) == 'string')
    {
        var txt = xmlDoc;
        if (window.DOMParser)
        {
            parser = new DOMParser();
            xmlDoc = parser.parseFromString(txt, "text/xml");
        }
        else // Internet Explorer
        {
            xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
            xmlDoc.async = "false";
            xmlDoc.loadXML(txt);
        } 
    }
    
    var attribute_inside = 0; /*:CONFIG: Value - 1 or 0
    *	If 1, Value and Attribute will be shown inside the tag - like this...
    *	For the XML string...
    *	<guid isPermaLink="true">http://www.bin-co.com/</guid>
    *	The resulting array will be...
    *	array['guid']['value'] = "http://www.bin-co.com/";
    *	array['guid']['attribute_isPermaLink'] = "true";
    *	
    *	If 0, the value will be inside the tag but the attribute will be outside - like this...	
    *	For the same XML String the resulting array will be...
    *	array['guid'] = "http://www.bin-co.com/";
    *	array['attribute_guid_isPermaLink'] = "true";
    */

    if(xmlDoc.nodeName && xmlDoc.nodeName.charAt(0) != "#") {
        if(xmlDoc.childNodes.length > 1) { //If its a parent
            arr = new Object;
            parent = xmlDoc.nodeName;
        }
    }
    var value = xmlDoc.nodeValue;
    if(xmlDoc.parentNode && xmlDoc.parentNode.nodeName && value) {
        if(not_whitespace.test(value)) {//If its a child
            arr = new Object;
            
            // Figure out the type of value
            if (! isNaN(parseFloat(value)))
                value = parseFloat(value);
            else if (! isNaN(parseInt(value, 10)))
                value = parseInt(value, 10);
            else if (typeof(value) == 'string' && value.toLowerCase() == 'false')
                value = false;
            else if (typeof(value) == 'string' && value.toLowerCase() == 'true')
                value = true;

            arr[xmlDoc.parentNode.nodeName] = value;
        }
    }

    if(xmlDoc.childNodes.length) {
        if(xmlDoc.childNodes.length == 1) { //Just one item in this tag.
            arr = xml_decode(xmlDoc.childNodes[0],parent_count); //:RECURSION:
        } else { //If there is more than one childNodes, go thru them one by one and get their results.
            var index = 0;

            for(var i=0; i<xmlDoc.childNodes.length; i++) {//Go thru all the child nodes.
                var temp = xml_decode(xmlDoc.childNodes[i],parent_count); //:RECURSION:
                if(temp) {
                    var assoc = false;
                    var arr_count = 0;
                    for(key in temp) {
                        if(isNaN(key)) assoc = true;
                        arr_count++;
                        if(arr_count>2) break;//We just need to know wether it is a single value array or not
                    }

                    if(assoc && arr_count == 1) {
                        if(arr[key]) { 	//If another element exists with the same tag name before,
                                        //		put it in a numeric array.
                            //Find out how many time this parent made its appearance
                            if(!parent_count || !parent_count[key]) {
                                parent_count[key] = 0;

                                var temp_arr = arr[key];
                                arr[key] = [];
                                arr[key].push(temp_arr);
                            }
                            parent_count[key]++;
                            arr[key][parent_count[key]] = temp[key]; //Members of of a numeric array
                        } else {
                            parent_count[key] = 0;
                            arr[key] = temp[key];
                            if(xmlDoc.childNodes[i].attributes && xmlDoc.childNodes[i].attributes.length) {
                                for(var j=0; j<xmlDoc.childNodes[i].attributes.length; j++) {
                                    var nname = xmlDoc.childNodes[i].attributes[j].nodeName;
                                    if(nname) {
                                        /* Value and Attribute inside the tag */
                                        if(attribute_inside) {
                                            var temp_arr = arr[key];
                                            arr[key] = new Object;
                                            arr[key]['value'] = temp_arr;
                                            arr[key]['@'+nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
                                        } else {
                                        /* Value in the tag and Attribute otside the tag(in parent) */
                                            arr['@' + key + '_' + nname] = xmlDoc.childNodes[i].attributes[j].nodeValue;
                                        }
                                    }
                                } //End of 'for(var j=0; j<xmlDoc. ...'
                            } //End of 'if(xmlDoc.childNodes[i] ...'
                        }
                    } else {
                        arr[index] = temp;
                        index++;
                    }
                } //End of 'if(temp) {'
            } //End of 'for(var i=0; i<xmlDoc. ...'
        }
    }

    if(parent && arr) {
        var temp = arr;
        arr = new Object;
        
        arr[parent] = temp;
    }
    
    return arr;
}

// Simple JavaScript Templating
// John Resig - http://ejohn.org/ - MIT Licensed
(function(){
  var cache = {};
 
  this.tmpl = function tmpl(str, data){
    // Figure out if we're getting a template, or if we need to
    // load the template - and be sure to cache the result.
    var fn = !/\W/.test(str) ?
      cache[str] = cache[str] ||
        tmpl(document.getElementById(str).innerHTML) :
     
      // Generate a reusable function that will serve as a template
      // generator (and which will be cached).
      new Function("obj",
        "var p=[],print=function(){p.push.apply(p,arguments);};" +
       
        // Introduce the data as local variables using with(){}
        "with(obj){p.push('" +
       
        // Convert the template into pure JavaScript
        str
            //.replace(/[\r\t\n]/g, " ")
            .replace(/[\r]/g, "\\r")
            .replace(/[\t]/g, "\\t")
            .replace(/[\n]/g, "\\n")
            .replace(/'(?=[^%]*%>)/g,"(((VARNAME)))")
            .split("'").join("\\'")
            .split("(((VARNAME)))").join("'")
            .replace(/<%=(.+?)%>/g, "',$1,'")
            .split("<%").join("');")
            .split("%>").join("p.push('")
        + "');}return p.join('');");
   
    // Provide some basic currying to the user
    return data ? fn( data ) : fn;
  };
})();




$(function ()
{
    function logout()
    {
        var a = $("#header .logout a");
        
        if ($.app && $.app.user && $.app.user.facebookUser)
        {
            FB.getLoginStatus(function(response)
            {
                if (response.status == 'connected')
                {
                    // logged in and connected user - Facebook user, use facebook logout and then Technopolis logout
                    FB.logout(function ()
                    {
                        document.location.href = $(a).attr('href');
                    })
                }
                else
                {
                    // Use Technopolis logout
                    document.location.href = $(a).attr('href');
                }
            });
        }
        else
            document.location.href = $(a).attr('href');
    }
    
    if ($("#header .facebook").length == 0)
    {
        // User logged in
        
        // Check if user is still logged in to Facebook, and if not - logout
        if ($.app && $.app.user && $.app.user.facebookUser)
            FB.getLoginStatus(function(response)
            {
                if (response.status != 'connected')
                    logout();
            });
        
        // Logout link
        $("#header .logout a").click(function ()
        {
            logout();
            return false;
        });
    }
    else
    {
        // User not logged in
        
        // Check if user is already logged in facebook, and if so - try to log him in our page as well
        $.app.fbLogin();
    }
});
// End Facebook login button



// Technopolis jQuery plugins (controllers)

// Keep a cache of these controllers instances, so that we only
// instantiate a controller for a specific DOM element once
function getController(controllerName, constructor, elem)
{
    if (! getController._inst)
        getController._inst = {};
    if (! getController._inst[controllerName])
        getController._inst[controllerName] = {};
    if (! getController._inst[controllerName][elem])
        getController._inst[controllerName][elem] = constructor.apply(elem[0]);

    return getController._inst[controllerName][elem];
}

$.fn.extend({
    "appCtrl" : function ()
    {
        var elem = $(this);
        var plugins = {
            "newMessage" : function ()
            {
                var constructor = function ()
                {
                    var self = {};
                    
                    var form1_new_message = $(this);
                    var form = $("form", form1_new_message);
                    var lastKey;
                    var timeout;
                    var popupDiv;
                    
                    var recipientsDiv = $('<div class="recipients-list"></div>');
                    $("input[name='recipients']", form1_new_message).after(recipientsDiv);
                    
                    function addRecipient(userId, userName)
                    {
                        var recipientsUserDiv = $('<span class="recipient"><span>'+userName+'</span><span class="delete"><span class="delete-in"></span></span></span>');
                        $(recipientsDiv).append(recipientsUserDiv);
                        
                        // Does the hidden input with user id already exist? (It will, if we are filling recipients div from those hidden inputs now)
                        // If it does not - create it
                        var hidden = $("input[name^='recipients['][value='"+userId+"']", form);
                        if (hidden.length == 0)
                        {
                            hidden = $('<input type="hidden" name="recipients[]" value="'+userId+'" />');
                            $(form).append(hidden);
                        }

                        $(".delete-in", recipientsUserDiv).click(function ()
                        {
                            $(hidden).remove();
                            $(recipientsUserDiv).remove();
                            lastKey = false;
                        });
                    }
                    
                    // If form was already posted - fill recipients-list
                    $("input[name^='recipientNames[']", form).each(function ()
                    {
                        addRecipient($(this).attr('name').replace(/^recipientNames\[/, '').replace(/\]$/, ''), $(this).val());
                    });
                    
                    $("input[name='recipients']", form1_new_message).focus(function ()
                    {
                        if (popupDiv)
                            $(popupDiv).show();
                    });
                    $(document).click(function ()
                    {
                        if ($("input[name='recipients']:focus", form1_new_message).length == 0)
                        {
                            if (popupDiv)
                                $(popupDiv).hide();
                            // popupDiv = false;
                        }
                    });
                    $("input[name='recipients']", form1_new_message).keydown(function ()
                    {
                        var input = $(this);
                        var key = $(input).val().trim();
                        
                        clearTimeout(timeout);
                        if (popupDiv)
                            $(popupDiv).remove();
                        
                        timeout = setTimeout(function ()
                        {
                            if (key != lastKey)
                            {
                                lastKey = key;
                                
                                if (key)
                                    $.post($.app.site_base_href + 'external/ajax/', {
                                        "fn": 'searchEmployees'
                                      , "key": key
                                    }, function (json)
                                    {
                                        if (json.success)
                                        {
                                            var list = json.list;
                                            list = $.grep(list, function (user) // Filter out users, that haven't yet been added
                                            {
                                                return $("input[name^='recipients['][value='"+user.id+"']", form).length == 0;
                                            });
                                            
                                            if (list && list.length > 0)
                                            {
                                                popupDiv = $('<div class="users-list-popup"></div>');
                                                $(input).after(popupDiv);
                                                
                                                $.each(list, function ()
                                                {
                                                    var user = this;
                                                    var div = $('<div></div>');
                                                    $(popupDiv).append(div);
                                                    
                                                    $(div).html(user.custom.employeeName);
                                                    $(div).hover(function ()
                                                    {
                                                        $(div).addClass('active');
                                                    }, function ()
                                                    {
                                                        $(div).removeClass('active');
                                                    });
                                                    $(div).click(function ()
                                                    {
                                                        $(input).val('');
                                                        lastKey = false;
                                                        
                                                        addRecipient(user.id, $(div).html());
                                                    });
                                                });
                                            }
                                        }
                                    }, 'json');
                            }
                        }, 500);
                    });
                    $("textarea[name='description']", form1_new_message).focus();
                    
                    self.clear = function ()
                    {
                        $("input[name='recipients']", form1_new_message).val('');
                        $("input[name^='recipients[']", form1_new_message).remove();
                        $(recipientsDiv).html('');
                        $("input[name='name']", form1_new_message).val('');
                        $("textarea[name='description']", form1_new_message).val('');
                    };
                    
                    self.recipients = function (list)
                    {
                        if (list)
                            $.each(list, function (index)
                            {
                                addRecipient(index, list[index]);
                            });
                    };
                    
                    return self;
                };
                
                return getController('AppControllerNewMessage', constructor, elem);
            }
        };
        
        return plugins;
    }
});


function appMinMaxClasses()
{
    // .width-max
    $(".width-max").each(function ()
    {
        var item = $(this);
        var parentWidth = ($(item).parent().cssInt('width') ? $(item).parent().cssInt('width') : $(item).parent().width());
        var siblingsWidth = 0;
        $(item).siblings().each(function ()
        {
            if ($(this).css('clear') == 'none' && this.nodeName.toLowerCase() != 'script')
                siblingsWidth += $(this).outerWidth(true);
        });
        
        $(item).css('width', parentWidth
                           - siblingsWidth
                           - $(item).cssInt('paddingLeft')
                           - $(item).cssInt('paddingRight')
                   );
    });
    
    $(".height-max").each(function ()
    {
        var item = $(this);
        var parentHeight = ($(item).parent().cssInt('height') ? $(item).parent().cssInt('height') : $(item).parent().height());
        var siblingsHeight = 0;
        $(item).siblings().each(function ()
        {
            if (this.nodeName.toLowerCase() != 'script')
                siblingsHeight += $(this).outerHeight(true);
        });

        $(item).css('height', parentHeight
                           - siblingsHeight
                           - $(item).cssInt('paddingTop')
                           - $(item).cssInt('paddingBottom')
                   );
    });
}

(function($)
{
    $.fn.rssReader = function (opt)
    {
        var elem = $(this);
        opt = $.extend({
            "limit": 20
        }, opt);
        
        $(function ()
        {
            if (opt.feed)
                $.post($.app.site_base_href + 'external/ajax/', {
                    "fn": 'getUrl'
                  , "url": opt.feed
                }, function (xmlText)
                {
                    var xml = xml_decode(xmlText);
                    var rss = (xml.rss ? xml.rss : (xml.channel ? xml : false));
                    if (rss)
                    {
                        try
                        {
                            rss.channel.item = rss.channel.item.slice(0, opt.limit);
                            $(elem).html(tmpl($("#rssReaderTpl").html(), {
                                "site_base_href": $.app.site_base_href
                              , "rss": rss
                            }));
                        } catch (err) {};
                        appMinMaxClasses();
                    }
                });
        });
    };


    $(function()
    {
        Cufon.replace('#header #header-top .site-title span', { fontFamily: 'AvantGarGotItcTOT-Dem' });
        // Cufon.replace('#header #header-top #menu-top .level1 .item span', { fontFamily: 'AvantGarGotItcTOT-Boo' });
        Cufon.replace('.home-content-block .home-content-block-top .title', { fontFamily: 'AvantGarGotItcTOT-ExtLig' });
        Cufon.replace('#header #header-top #menu-top .level2-home .sub .sub-title', { fontFamily: 'AvantGarGotItcTOT-ExtLig' });
        Cufon.replace('#header #header-area-title', { fontFamily: 'AvantGarGotItcTOT-ExtLig' });
        Cufon.replace('.photo-block .photo-block-info .photo-title', { fontFamily: 'AvantGarGotItcTOT-ExtLig' });



        $.alerts.okButton       = '&nbsp;' + $.app.lang.yes + '&nbsp;';
        $.alerts.cancelButton   = '&nbsp;' + $.app.lang.no + '&nbsp;';
        (function ()
        {
            var proxied = jAlert;
            jAlert = function ()
            {
                $.alerts.okButton = '&nbsp;' + $.app.lang.ok + '&nbsp;';
                proxied.apply(this, arguments);
                $.alerts.okButton = '&nbsp;' + $.app.lang.yes + '&nbsp;';
            };
        })();


        $.fn.cssInt = function (name)
        {
            var d = $(this).css(name);
            if (d)
            {
                d = d.replace(/px/, '');
                return Number(d);
            }
            
            return 0;
        };
        
    
        appMinMaxClasses();
        

        (function languages()
        {
            // .languages .other - we apply 3 shadow divs, each 1px bigger on all sides than the previous one,
            // and we give each of those divs a smaller alpha (opacity) value - this gives us a 3px size fading shadow.
            var languagesOther = $("#header #header-top #header-top-right .languages .other");
            languagesOther.wrapInner("<div></div>");
            var languagesOtherContent = $("> div", languagesOther);
            $(languagesOtherContent).css({
                "position": "absolute",
                "background": "#FFFFFF",
                "width": languagesOther.width()
            });
            
            var shadows = [0.046875, 0.0234375, 0.0078125]; // Shadow opacities
            languagesOther.show();
            for (var i = 0; i < shadows.length; i++)
            {
                var shadowDiv = $("<div></div>").css({
                    "position": "absolute",
                    "background": "#000000",
                    "opacity": shadows[i],
                    "width": languagesOtherContent.width() + (i * 2),
                    "height": languagesOtherContent.height() + (i * 2),
                    "marginTop": - i,
                    "marginLeft": - i
                });
                languagesOther.prepend(shadowDiv);
            }
            languagesOther.hide();
            
            
            // .languages - show on hover
            $("#header #header-top #header-top-right .languages").hover(
                function ()
                {
                    languagesOther.show();
                }
              , function ()
                {
                    languagesOther.hide();
                }
            );
        })();
        
        $(".page-home #menu-top").each(function ()
        {
            var menu_top = $(this);
            
            var itemsList = $(".level1 .item", menu_top);
            var aList = $(".level1 a", menu_top);
            var subList = $(".level2-home .sub", menu_top);
            $(itemsList).each(function ()
            {
                var item = $(this);
                var index = $(itemsList).index(item);
                var sub = $($(subList).get(index));
                
                function hoverOn()
                {
                    $(this).data('hover', true);
                    
                    $(aList).removeClass('item-active');
                    $(item).parent().addClass('item-active');
                    
                    $(subList).hide();
                    $(sub).show();
                }
                function hoverOff()
                {
                    $(this).data('hover', false);
                    
                    $(item).parent().removeClass('item-active');
                    
                    $(sub).hide();
                }
                
                $(item).hover(hoverOn, hoverOff);
                $(sub).hover(hoverOn, hoverOff);
            });
        });
        
        // Fix for IE6:
        $("#menu-top .level1 a").click(function ()
        {
            document.location.href = $(this).attr('href');
        });
        
        $("#search").each(function ()
        {
            var search = $(this);
            
            $(".input input").focus(function ()
            {
                if ($(this).val().trim() == 'Paieška')
                    $(this).val('');
            });
            $(".input input").blur(function ()
            {
                if ($(this).val().trim() == '')
                    $(this).val('Paieška');
            });
        });
        
        $(".tabbed").each(function ()
        {
            var tabbed = $(this);
            var tab_list = $(".tab-list", tabbed);
            var tabbed_content = $(".tabbed-content", tabbed);
            var tabsList = $(".tab", tab_list);
            var anchor = urlGetAnchor();

            $(tabsList).each(function ()
            {
                var tab = $(this);
                var index = $(tabsList).index(tab);
                
                $(tab).css('cursor', 'pointer');

                if (! $(tabbed).hasClass('tabbed-reload'))
                {
                    if (anchor)
                    {
                        var anchorParts = anchor.split('/');
                        if (anchorParts.length >= 2 && anchorParts[1].indexOf('tab-') === 0 && $(tab).hasClass(anchorParts[1]))
                        {
                            $(tab).addClass('tab-active');
                            $(".tab-content:eq("+index+")", tabbed_content).addClass('tab-content-active');
                        }
                    }

                    // var tabNames = $.grep($(tab)[0].className.split(/\s+/), function (name)
                    // {
                        // return name.indexOf('tab-') === 0;
                    // });
                    
                    $(tab).click(function ()
                    {
                        $(tabsList).removeClass('tab-active');
                        $(tab).addClass('tab-active');
                        
                        $(".tab-content", tabbed_content).removeClass('tab-content-active');
                        $(".tab-content:eq("+index+")", tabbed_content).addClass('tab-content-active');
                        // if (tabNames.length > 0)
                            // document.location.href = urlChangeAnchor(tabNames[0]);
                    });
                }
            });
            
            if ($(".tab-active", tab_list).length == 0)
            {
                $(".tab:first", tab_list).addClass('tab-active');
                $(".tab-content:first", tabbed_content).addClass('tab-content-active');
            }
        });
        
        $("#news-summary").each(function ()
        {
            var news_summary = $(this);
            var list = $(".list .item", news_summary);
            
            if ($(list).length > 1)
            {
                var index = 0;
                var timer = false;
                var TIME = 6000;
                
                function showItem(itemIndex)
                {
                    index = itemIndex % $(list).length;
                    var item = $(list).get(index);

                    $(list).fadeOut('slow', function ()
                    {
                        $(this).removeClass('item-active');
                    });

                    $(item).show('slide', {}, 'slow', function ()
                    {
                        $(this).addClass('item-active');
                    });
                }
                
                timer = setTimeout(function ()
                {
                    showItem(index + 1);
                    timer = setTimeout(arguments.callee, TIME);
                }, TIME);
            }
        });
        
        $(".home-partners").each(function ()
        {
            var home_partners = $(this);
            var pairWidth = $(".home-partners-top-content-pair:first", home_partners).width();
            var count = $(".home-partners-top-content-pair", home_partners).length;
            
            var index = 0;
            
            function updateIndex()
            {
                $(".home-partners-top-content-in", home_partners).css({
                    "marginLeft": - (pairWidth * index)
                });
            }
            
            function slideTo(diff)
            {
                // If there are no sliding motions running right now, try to cleanup slider from redundand elements
                // (there can be redundant elements on the right).
                if ($(".home-partners-top-content-in", home_partners).queue().length == 0)
                {
                    if (index >= count)
                    {
                        index %= count;
                        updateIndex();
                    }
                    
                    $(".home-partners-top-content-pair:gt("+count+")", home_partners).remove();
                    $(".home-partners-top-content-pair:eq("+count+")", home_partners).remove();
                }
                
                // If there are no more item pairs in the direction we are moving - take the first pair on
                // the other side and put it there
                var next = index + diff;
                if (next >= count)
                {
                    $(".home-partners-top-content-pair:eq(" + (next % count) + ")", home_partners)
                        .clone()
                        .appendTo($(".home-partners-top-content-in", home_partners));
                }
                if (next < 0)
                {
                    var left = Number($(".home-partners-top-content-in", home_partners).css('marginLeft').replace(/px/, ''));
                    
                    $(".home-partners-top-content-pair:eq(" + (count - (-next)) + ")", home_partners)
                        .clone()
                        .prependTo($(".home-partners-top-content-in", home_partners));
                    
                    $(".home-partners-top-content-in", home_partners).css({
                        "marginLeft": left - pairWidth
                    });
                    
                    next += 1;
                }
                
                $(".home-partners-top-content-in", home_partners).stop().animate({
                    "marginLeft": - (pairWidth * next)
                });
                
                index = next;
            }
            
            $(".button-left", home_partners).css('cursor', 'pointer');
            $(".button-left", home_partners).click(function ()
            {
                slideTo(-1);
            });
            
            $(".button-right", home_partners).css('cursor', 'pointer');
            $(".button-right", home_partners).click(function ()
            {
                slideTo(1);
            });
        });
        
        $(".events-calendar").each(function ()
        {
            var events_calendar = $(this);
            var input = $('input', events_calendar);
            
            var datepicker = false;
            
            // Localization copied from l18n and moved here, because otherwise there
            // is a delay before it is loaded
            $.datepicker.regional['lt'] = {
                closeText: 'Uždaryti',
                prevText: '&#x3c;Atgal',
                nextText: 'Pirmyn&#x3e;',
                currentText: 'Šiandien',
                monthNames: ['Sausis','Vasaris','Kovas','Balandis','Gegužė','Birželis',
                    'Liepa','Rugpjūtis','Rugsėjis','Spalis','Lapkritis','Gruodis'],
                monthNamesShort: ['Sau','Vas','Kov','Bal','Geg','Bir',
                    'Lie','Rugp','Rugs','Spa','Lap','Gru'],
                dayNames: ['sekmadienis','pirmadienis','antradienis','trečiadienis','ketvirtadienis','penktadienis','šeštadienis'],
                dayNamesShort: ['sek','pir','ant','tre','ket','pen','šeš'],
                dayNamesMin: ['S','P','A','T','K','P','Š'],
                weekHeader: 'Wk',
                dateFormat: 'yy-mm-dd',
                firstDay: 1,
                isRTL: false,
                showMonthAfterYear: false,
                yearSuffix: ''
            };
            
            // Extend $.datepicker._updateDatepicker to add a custom calendar legend, by using a proxy function
            (function()
            {
                var proxied = $.datepicker._updateDatepicker;
                $.datepicker._updateDatepicker = function(instance)
                {
                    proxied.apply(this, arguments);
                    
                    $(datepicker.dpDiv).append(
                        '<div class="events-calendar-legend">'
                      + '   <div class="fl">'
                      + '       <div class="fl legend-events dib"><!-- --></div>'
                      + '       <div class="fl">' + $('.eventsTitle', events_calendar).html() + '</div>'
                      + '   </div>'
                      + '   <div class="fr">'
                      + '       <div class="fl legend-today dib"><!-- --></div>'
                      + '       <div class="fl">Šiandien</div>'
                      + '   </div>'
                      + '   <div class="clear"><!-- --></div>'
                      + '</div>'
                    );
                    
                    // Show event days
                    var reload = true;
                    var year = instance.selectedYear;
                    var month = instance.selectedMonth + 1;
                    if ($.app && $.app.events && $.app.events[year])
                    {
                        if ($.app.events[year][month] !== undefined)
                        {
                            reload = false;
                            
                            $($.app.events[year][month]).each(function ()
                            {
                                var day = this.split('-');
                                day = day[2] - 1;
                                $(".ui-datepicker td:not(.ui-datepicker-other-month):eq(" + day + ")").addClass('ui-datepicker-event');
                            });
                        }
                    }
                    
                    if (reload)
                    {
                        $.post($.app.site_base_href + 'external/ajax/', {
                            "fn": 'getMonthEvents'
                          , "month": year + '-' + month
                        }, function (json)
                        {
                            if (json.success)
                            {
                                if (! $.app.events[year])
                                    $.app.events[year] = {};
                                $.app.events[year][month] = json.list;
                                $.datepicker._updateDatepicker(instance);
                            }
                        }, 'json');
                    }
                };
            })();
            
            var opt = $.datepicker.regional.lt;
            opt = $.extend({
                "beforeShow": function(input, inst)
                {
                    datepicker = inst;
                }
              , "showAnim": ''
              , "onSelect": function(dateText, inst)
                {
                    var date = Date.today().set({
                        day: Number(inst.selectedDay),
                        month: Number(inst.selectedMonth),
                        year: Number(inst.selectedYear)
                    });
                    document.location.href = urlChangeParam($(input).attr('name')
                                                          , date.toString("yyyy-MM-dd")
                                                          , $.app.pages.events.url);
                }
            }, opt);
            
            $(input).show();
            $(input).datepicker(opt);
            $(input).datepicker('show');
            $(input).hide();
            
            $(events_calendar).append(datepicker.dpDiv);
            $(datepicker.dpDiv).css({
                "position": 'static'
              , "width": null
            });
            $(datepicker.dpDiv).removeClass('ui-corner-all');
            
            // Trick datepicker into thinking it is not currently shown,
            // so that it would not automatically hide, when user clicks somewhere in the page
            $.datepicker._datepickerShowing = false;
        });
        
        $(".photo-block").each(function ()
        {
            var photo_block = $(this);
            var photos = $(".photo-block-list .item", photo_block);
            var photosInfo = $(".photo-block-info-list .item", photo_block);
            var choosers = $(".photo-block-chooser .item", photo_block);
            var index = 0;
            var timer = false;
            var TIME = 10000;
            
            function showItem(itemIndex)
            {
                index = itemIndex % $(photos).length;
                
                $(photos).removeClass('item-active');
                $($(photos).get(index)).addClass('item-active');
                $(photosInfo).removeClass('item-active');
                $($(photosInfo).get(index)).addClass('item-active');
                $(choosers).removeClass('item-active');
                $($(choosers).get(index)).addClass('item-active');
            }
            
            
            $(choosers).each(function ()
            {
                var item = $(this);
                var itemIndex = $(choosers).index(item);
                
                $(item).css('cursor', 'pointer');
                $(item).click(function ()
                {
                    clearTimeout(timer);
                    showItem(itemIndex);
                });
            });
            
            timer = setTimeout(function ()
            {
                showItem(index + 1);
                timer = setTimeout(arguments.callee, TIME);
            }, TIME);
        });
        
        $(".content-main").each(function ()
        {
            var content_main = $(this);
            
            $(".text-size .text-size-plus").css('cursor', 'pointer');
            $(".text-size .text-size-plus").click(function ()
            {
                $(".wysiwyg", content_main).css('fontSize', $(".wysiwyg", content_main).cssInt('fontSize') + 1);
            });
            
            $(".text-size .text-size-minus").css('cursor', 'pointer');
            $(".text-size .text-size-minus").click(function ()
            {
                $(".wysiwyg", content_main).css('fontSize', $(".wysiwyg", content_main).cssInt('fontSize') - 1);
            });
        });
        
        $(".form1").each(function ()
        {
            var form1 = $(this);
            
            function initField()
            {
                var field           = $(this);
                var defaultValue    = $(".default-value", field).html();
                var inputs          = $(".field-input input, .field-input textarea, .field-input select", field);
                
                $(inputs).focus(function ()
                {
                    $(".field-tooltip", field).show();
                    if (defaultValue && $(this).val().trim() == defaultValue)
                        $(this).val('');
                }).blur(function ()
                {
                    $(".field-tooltip", field).hide();
                    if (defaultValue && $(this).val().trim() == '')
                        $(this).val(defaultValue);
                });
            }
            
            $(".field", form1).each(initField);
            
            $(".section-members", form1).each(function ()
            {
                var section_members = $(this);
                
                $(".plus", section_members).css('cursor', 'pointer');
                $(".plus", section_members).click(function ()
                {
                    var members_item = $(".members-item:last", section_members).clone();
                    var itemIndex = $(".members-item", section_members).length;
                    
                    $(".members-number", members_item).html((itemIndex + 1) + '.');
                    $(".field .field-input", members_item).each(function ()
                    {
                        $('input', this).val($(".default-value", this).html());
                        $('input', this).attr('name', $('input', this).attr('name').replace(/members\[(\d+)\]/, 'members[' + itemIndex + ']'));
                    });
                    $(".field", members_item).each(initField);
                    $(".members-item:last", section_members).after(members_item);
                });
            });
        });
        
        $(".form1-login").each(function ()
        {
            var form1_login = $(this);
            
            function updateType()
            {
                var type = $("input[name='type']:checked", form1_login).val();

                if (type == 1) // Login
                {
                    $(".input-register", form1_login).hide();
                    $(".input-login", form1_login).show();
                }
                else
                {
                    $(".input-login", form1_login).hide();
                    $(".input-register", form1_login).show();
                }
            }
            updateType();
            $("input[name='type']", form1_login).change(updateType);
        });
        
        $(".form1-new-message").each(function ()
        {
            $(this).appCtrl().newMessage();
        });
        
        $(".gallery-images").each(function ()
        {
            var events_gallery_list = $(this);
            
            $(".item", events_gallery_list).hover(function ()
            {
                $(this).addClass('item-hover');
            }, function ()
            {
                $(this).removeClass('item-hover');
            });
        });
        
        $(".order-form").each(function ()
        {
            var order_form = $(this);
            var table = $("table", order_form);
            
            function itemRow()
            {
                var row = $(this);
                
                function calcTotal()
                {
                    var price   = Number($("input[name$='price]']", row).val().replace(',', '.')) || 0;
                    var amount  = Number($("input[name$='amount]']", row).val().replace(',', '.')) || 0;
                    $("input[name$='total]']", row).val((price * amount).toFixed(2));
                    
                    var totalAmount = 0;
                    $("input[name$='total]']", order_form).each(function ()
                    {
                        totalAmount += Number($(this).val());
                    });
                    $(".total_amount", order_form).html(totalAmount + ' Lt');
                }
                calcTotal();
                $("input[name$='price]']", row).change(calcTotal);
                $("input[name$='amount]']", row).change(calcTotal);
            }
            
            $("tr.item").each(itemRow);
            
            $(".plus", table).css('cursor', 'pointer');
            $(".plus", table).click(function ()
            {
                var numberRows = $("tr:has(.num)", table).length;
                var row = $("tr:has(.num):first", table).clone();
                $(row).removeClass('item-error');
                $(".num", row).html((numberRows + 1) + '.');
                $("input", row).val('');
                $("input[name$='name]']", row).attr('name', 'products['+numberRows+'][name]');
                $("input[name$='price]']", row).attr('name', 'products['+numberRows+'][price]');
                $("input[name$='amount]']", row).attr('name', 'products['+numberRows+'][amount]');
                $("input[name$='total]']", row).attr('name', 'products['+numberRows+'][total]');
                
                $("tr:has(.num):last", table).after(row);
                $(row).each(itemRow);
            });
        });
        
        function showTab(tabbed, tabName)
        {
            var tabIndex = $(".tab", tabbed).index($(".tab-" + tabName, tabbed));
            $(".tab", tabbed).removeClass('tab-active');
            $(".tab-content", tabbed).removeClass('tab-content-active');

            var anchor = urlGetAnchor();
            if (anchor)
            {
                var anchorParts = anchor.split('/');
                if (anchorParts.length >= 2 && anchorParts[1].indexOf('tab-') === 0)
                    document.location.href = urlChangeAnchor(['', 'tab-' + tabName].join('/'));
            }
            
            if (tabIndex >= 0)
            {
                $(".tab:eq(" + tabIndex + ")", tabbed).addClass('tab-active');
                $(".tab-content:eq(" + tabIndex + ")", tabbed).addClass('tab-content-active');
            }
        }
        
        $(".messages-list").each(function ()
        {
            var messages_list = $(this);
            
            // var messagesListAnchor = $.grep($(messages_list)[0].className.split(/\s+/), function (name)
            // {
                // return name.indexOf('messages-list-') === 0;
            // });
            // var anchorBase = false;
            // if (messagesListAnchor && messagesListAnchor == 'messages-list-incoming')
                // anchorBase = '/tab-incoming';
            // else if (messagesListAnchor && messagesListAnchor == 'messages-list-outgoing')
                // anchorBase = '/tab-outgoing';

            $("table tr:has(.type)", messages_list).each(function ()
            {
                var tr = $(this);
                var id = $("input[name='messages[]']", tr).val();
                var message_text = $(tr).next();
                
                $(tr).css('cursor', 'pointer');
                $("input", tr).click(function (evt)
                {
                    evt.stopPropagation();
                });

                // // If we are on a freshly opened page - try to open correct message from the page anchor
                // if (anchorBase)
                // {
                    // var anchor = urlGetAnchor();
                    // if (anchor)
                    // {
                        // var anchorParts = anchor.split('/');
                        // if (anchorParts.length >= 3 && ('/' + anchorParts[1]) == anchorBase && anchorParts[2] == id)
                            // $(message_text).show();
                    // }
                // }
                
                $(".delete-message-btn", message_text).click(function ()
                {
                    jConfirm('Ar tikrai ištrinti žinutę?', 'Patvirtinimas', function (r)
                    {
                        if (r)
                        {
                            $("form input[name='action']", messages_list).val('delete');
                            $("form input:checked", messages_list).attr('checked', false);
                            $("input[name='messages[]']", tr).attr('checked', true);
                            $("form", messages_list).submit();
                        }
                    });
                    
                    return false;
                });
                $(".reply-btn", message_text).click(function ()
                {
                    $("form input[name='action']", messages_list).val('reply');
                    $("form input:checked", messages_list).attr('checked', false);
                    $("input[name='messages[]']", tr).attr('checked', true);
                    $("form", messages_list).submit();
                    
                    return false;
                });
                
                $(":not(.message-text)", tr).click(function (evt)
                {
                    if (! evt.isPropagationStopped())
                    {
                        document.location.href = $(tr).attr('href');
                        
                        // Stop propagation, otherwise this click event may be fired on a few different elements
                        // of this message row, cancelling them out (one click opens a row, aonother one - closes)
                        evt.stopPropagation();
                    }
                });
            });
            
            $(".delete-btn", messages_list).click(function ()
            {
                jConfirm('Ar tikrai ištrinti pažymėtas žinutes?', 'Patvirtinimas', function (r)
                {
                    if (r)
                    {
                        $("form input[name='action']", messages_list).val('delete');
                        $("form", messages_list).submit();
                    }
                });
                
                return false;
            });
        });
        
        $(".message").each(function ()
        {
            var message = $(this);
            
            $(".delete-btn", message).click(function ()
            {
                jConfirm('Ar tikrai ištrinti žinutę?', 'Patvirtinimas', function (r)
                {
                    if (r)
                    {
                        var form = $('<form method="POST" />');
                        $(form).attr('action', document.location.href);
                        
                        $(form).append('<input type="hidden" name="form_id" value="message" />');
                        $(form).append('<input type="hidden" name="action" value="delete" />');
                        
                        $(form).submit();
                    }
                });
                
                return false;
            });
            
            $(".reply-btn", message).click(function ()
            {
                var id = $(".id", message).html();
                
                var form = $('<form method="POST" />');
                $(form).attr('action', document.location.href);
                
                $(form).append('<input type="hidden" name="form_id" value="message" />');
                $(form).append('<input type="hidden" name="action" value="reply" />');
                
                $(form).submit();
            });
        });

        $(".announcements-list").each(function ()
        {
            var announcements_list = $(this);
            
            $(".table1 tr.item", announcements_list).each(function ()
            {
                var tr = $(this);
                
                $(tr).css('cursor', 'pointer');
                $(tr).click(function ()
                {
                    document.location.href = $(tr).attr('href');
                });
            });
        });
        
        $(".forum").each(function ()
        {
            var forum = $(this);
            
            $(".forum-filter select", forum).change(function ()
            {
                document.location.href = $(this).val();
            });
            
            var trackInputs = $(".track .input input");
            $(trackInputs).click(function ()
            {
                var track = $(this).is(":checked");

                $.post($.app.site_base_href + 'external/ajax/', {
                    "fn": 'trackDiscussion'
                  , "id": $(trackInputs).val()
                  , "val": (track ? 1 : 0)
                }, function (json)
                {
                    if (json.success)
                        $(trackInputs).attr('checked', track);
                }, 'json');
                
                return false;
            });
            
            
            $(".forum-topic, .comment", forum).each(function ()
            {
                var forum_entry = $(this);
                var id          = $('.reply_id', forum_entry).html();   
                var anchor      = urlGetAnchor();
                
                function blinkBackground(elem, color, times, first)
                {
                    if (first === undefined)
                        first = true;
                    
                    if (times > 0)
                    {
                        var backgroundImage = $(elem).css('background-image');
                        $(elem).css('background-image', 'none');

                        function fadeBack()
                        {
                            $(elem).animate({
                                "background-color": '#FFFFFF'
                            }, 'slow', function ()
                            {
                                $(elem).css('background-image', backgroundImage);
                                blinkBackground(elem, color, (times - 1), false);
                                if (times - 1 <= 0)
                                    $(elem).css('background-image', backgroundImage);
                            });
                        }
                        
                        if (first)
                        {
                            $(elem).css({
                                "background-color": color
                            });
                            fadeBack();
                        }
                        else
                            $(elem).animate({
                                "background-color": color
                            }, 'slow', fadeBack);
                    }
                }
                
                if (id == anchor)
                    blinkBackground(forum_entry, '#AEFEE1', 3);
                
                $(".comment-info .text a", forum_entry).click(function ()
                {
                    if ($(this).attr('href').slice(0, 1) == '#')
                    {
                        var anchor      = $(this).attr('href').slice(1);
                        var linkedEntry = $(".comments-list .comment:has(.reply_id_" + anchor + "), .forum-topic:has(.reply_id_" + anchor + ")", forum);
                        if (linkedEntry.length > 0)
                            blinkBackground(linkedEntry, '#AEFEE1', 3);
                    }
                    
                    return true;
                });
                
                $(".reply-btn", forum_entry).css('cursor', 'pointer');
                $(".reply-btn", forum_entry).click(function ()
                {
                    $(".new-comment input[name='reply_id']", forum).val(id);
                    
                    var username = false;
                    if ($(".username a", forum_entry).length > 0)
                        username = $(".username a", forum_entry).html().trim();
                    else if ($(".username", forum_entry).length > 0)
                        username = $(".username", forum_entry).html().trim();
                    
                    if (username)
                    {
                        $(".new-comment textarea", forum).val('@' + username + '\n');
                        $(".new-comment textarea", forum).focus();
                        setSelRange($(".new-comment textarea", forum)[0], $(".new-comment textarea", forum).val().length, $(".new-comment textarea", forum).val().length)
                    }
                });
            });
        });
        
        $(".gallery-images").each(function ()
        {
            var events_gallery_list = $(this);
            
            if (! $(events_gallery_list).hasClass('events-gallery-list'))
                $('.item a', events_gallery_list).fancybox({
                    'transitionIn'  : 'elastic'
                  , 'transitionOut' : 'elastic'
                  , 'titlePosition'	: 'over'
                });
        });
        
        $(".user-profile-edit").each(function ()
        {
            var user_profile_edit = $(this);
            
            function updateCompanyName()
            {
                if (Number($("input[name='technopolisEmployee']:checked", user_profile_edit).val()))
                {
                    $(".field:has(select[name='company_id'])", user_profile_edit).show();
                    $(".field:has(input[name='companyName'])", user_profile_edit).hide();
                }
                else
                {
                    $(".field:has(select[name='company_id'])", user_profile_edit).hide();
                    $(".field:has(input[name='companyName'])", user_profile_edit).show();
                }
            }
            updateCompanyName();
            $("input[name='technopolisEmployee']", user_profile_edit).change(updateCompanyName);
        });
        
        $(".forum-edit-topic .attachments").each(function ()
        {
            var attachments = $(this);
            
            function clearItem(item)
            {
                $(".attachments-item-type select option:selected", item).attr('selected', false);
                $(".attachments-item-url input", item).val('');
            }
            
            function initItem(item)
            {
                $(".attachments-item-delete img", item).css('cursor', 'pointer');
                $(".attachments-item-delete img", item).click(function ()
                {
                    if ($(".attachments-item", attachments).length > 1)
                        $(item).remove();
                    else
                        clearItem(item);
                });
            }
            
            $(".attachments-item", attachments).each(function ()
            {
                initItem(this);
            });
            
            $(".add-attachment", attachments).css('cursor', 'pointer');
            $(".add-attachment", attachments).click(function ()
            {
                var attachments_item = $(".attachments-item:last", attachments).clone();
                var itemIndex = $(".attachments-item", attachments).length;
                
                $("input, select", attachments_item).each(function ()
                {
                    $(this).attr('name', $(this).attr('name').replace(/attachments\[(\d+)\]/, 'attachments[' + itemIndex + ']'));
                });
                $(".attachments-item:last", attachments).after(attachments_item);
                clearItem(attachments_item);
                initItem(attachments_item);
            });
        });
        
        $(".comments-list").each(function ()
        {
            var comments_list = $(this);
            
            $(".comment", comments_list).each(function ()
            {
                var comment = $(this);
                
                $(".bad-comment a", comment).click(function ()
                {
                    jConfirm($.app.lang.is_comment_bad, $.app.lang.confirmation, function (r)
                    {
                        if (r)
                        {
                            var username = '';
                            if ($(".username a", comment).length > 0)
                                username = $(".username a", comment).html().trim();
                            else if ($(".username", comment).length > 0)
                                username = $(".username", comment).html().trim();
                            
                            $.post($.app.site_base_href + 'external/ajax/', {
                                "fn": 'badComment'
                              , "url": document.location.href
                              , "username": username
                              , "text": $(".text", comment).html().trim()
                            }, function (json)
                            {
                                if (json.success)
                                    jAlert($.app.lang.administrator_informed, $.app.lang.thank_you);
                            }, 'json');
                        }
                    });
                    
                    return false;
                });
            });
        });
    });
})(jQuery);
