
$(document).ready(function () {
    // Lazy load plugins
    $.lazy({ src: '/javascripts/jquery/jquery.valid8.js', name: 'valid8', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.uploadify.v2.0.2.js', name: 'uploadify', cache: true });
    $.lazy({ src: '/javascripts/jquery/easySlider1.5.js', name: 'easySlider', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.tabify.min.js', name: 'tabify', cache: true });
    $.lazy({ src: '/javascripts/jquery/easyTooltip.js', name: 'easyTooltip', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.defaultvalue.js', name: 'defaultValue', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.elastic.source.js', name: 'elastic', cache: true });
    $.lazy({ src: '/javascripts/jquery/facebox.js', name: 'facebox', dependencies: {
        'css': ['/style/facebox.css']
    }, cache: true
    });
    $.lazy({ src: '/javascripts/jquery/jquery.scrollTo-1.4.2-min.js', name: 'scrollTo', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.showpassword-1.0.js', name: 'showPassword', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.limit-1.2.js', name: 'limit', cache: true });
    $.lazy({ src: '/javascripts/jquery/colorbox/jquery.colorbox-min.js', name: 'colorbox', cache: true, dependencies: { css: ['/javascripts/jquery/colorbox/css/colorbox.css']} });
    $.lazy({ src: '/javascripts/jquery/jquery.uniform.min.js', name: 'uniform', cache: true });
    $.lazy({ src: '/javascripts/jquery/jquery.tools.min.js', name: 'overlay', cache: true });
	
	// Insert at carret
	jQuery.fn.extend({
insertAtCaret: function(myValue){
  return this.each(function(i) {
    if (document.selection) {
      this.focus();
      sel = document.selection.createRange();
      sel.text = myValue;
      this.focus();
    }
    else if (this.selectionStart || this.selectionStart == '0') {
      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();
    }
  })
}
});

    if ($('.button-v2.new-discussion').length > 0 && $('ul.feed.forum .add-new').length > 0) {
        $.getScript("/javascripts/volvo.forum.discussion.js");
    }
    
    // Add to youtube button
    $('.add-youtube-link').live('click', function(){
    	var link = prompt('Youtube link:');
    	if(link){
    		$( $(this).attr('rel') ).insertAtCaret('[youtube]' + link + '[/youtube]');
    	}
    });

    if ($('.minButton.addNewLanguage').length > 0) {
        $.getScript("/javascripts/volvo.forum.filter.js");
    }

    //Ok-message
    setTimeout(function () {
        $('.ok-message').fadeOut('slow', function () {
            $(this).remove();
        });
    }, 5000);


    // Initiate corners
    $('.cornered').append('<div class="corner tr"> \</div><div class="corner br"></div><div class="corner bl"></div><div class="corner tl"></div>');

    //Initiate tooltips
    $('.pageContent a.tooltiped').easyTooltip();
    $('.pageHeader .friendRequests.tooltiped').easyTooltip({ 'tooltipId': 'friendRequestsTooltip', 'yOffset': '-10' });
    $('.pageHeader .groupRequests.tooltiped').easyTooltip({ 'tooltipId': 'groupRequestsTooltip', 'yOffset': '-10' });

    //Initiate elastic
    $('textarea.elastic').elastic();

    //Fix menu	
    //$('#signInPanel').css({'width':$('#userMenuWrapperRight').width()-20});
	
	
	//Generator limit
	if ($('.generator textarea[name=description]').length > 0) {
		$('.generator textarea[name=description]').limit('140', '#generatorDescriptionCharsLeft');
	}
	if ($('.generator textarea[name=message]').length > 0) {
		$('.generator textarea[name=message]').limit('140', '#generatorMessageCharsLeft');
	}
	if ($('#worldTruckerShare textarea').length > 0) {
		$('#worldTruckerShare textarea').limit('140', '#worldTruckerShareCharsLeft');
	}
	

    //Lates post in forum current
    $('.latestPosts .profilePhoto').bind('click', function (e) {
        $this = $(this);
        $other = $this.closest('.latestPosts').find('.profilePhoto');
        $other.removeClass('current');
        $this.addClass('current');
    });


    //Default value, without plugin
    $('input, textarea').each(function () {
        var $this = $(this);
        var originalValue = $this.data('originalValue');

        if (originalValue !== '' && typeof (originalValue) !== 'undefined' && $this.val() === '') {
            $this.val(originalValue);
        }
    });
    $('input, textarea').bind('focus', function () {
        var $this = $(this);
        var originalValue = '' + $this.data('originalValue');

        if ($this.val() === originalValue && originalValue !== '' && typeof (originalValue) !== 'undefined') {
            $this.val('');
        }
    });
    $('input, textarea').bind('blur', function () {
        var $this = $(this);
        var $tooltip = $this.data('tooltip');
        var originalValue = $this.data('originalValue');

        if ($this.val() === '' && originalValue !== '' && typeof (originalValue) !== 'undefined') {
            $this.val(originalValue);
        }
    });


    //User Menu
    $('#menuButtonSignIn').click(function () {
        $('#signInCorner').css({ 'width': $('#menuButtonSignIn').width() + 6 });
        $(this).toggleClass('open');
        $('#menuPanelSignIn').toggle();
        if ($('#menuPanelSignIn').is(':visible')) {
            $('#signInPanelInputEmail').focus();
        }
    });

    $('.userMenuPanel ul.feed').parents('li').find('a').addClass('cursor-pointer');

    $('.userMenu > li > a:not(.settings, .signOut, .signIn)').click(function (e) {
        e.preventDefault();
        $this = $(this);
        $parent = $this.closest('li');
        if ($parent.find('.userMenuPanel').length > 0) {
            $notifications = $parent.find('.userMenuPanel');
            $menuLeft = $('#userMenuWrapperLeft');

            $('.userMenuPanel').not($notifications).hide();

            $this.toggleClass('open');
            $notifications.css({ 'width': $menuLeft.width() });
            $notifications.toggle();

            $('body').bind('click.outside', function (e) {
                var parentElement = $parent[0];
                if (!$.contains(parentElement, e.target)) {

                    //Only if notification
                    if ($this.hasClass('notifications')) {
                        $.ajax({
                            type: "POST",
                            url: "/services/Notifications.asmx/SetNotificationRead",
                            success: function (msg) {
                                $parent.removeClass('active');
                                $this.find('.right').text($this.data('zeroValue'));
                                $notifications.hide();
                                $('body').unbind('click.outside');
                            }
                        });
                    }
                    else {
                        $notifications.hide();
                        $('body').unbind('click.outside');
                    }
                }
            });
        }
    });

    $('.userMenu > li.expand').find('a').trigger('click');


    $('.ajaxLoader').live('click', function (e) {

        $(this).addClass('loading');

        $(window).bind($(this)[0].id, function () {
            $(this).removeClass('loading');
        });
    });


    /*Show comments*/
    $('.action > .comment > a').live('click', function (e) {
        e.preventDefault();
        var $this = $(this);
        var $commentBox = $this.closest('.feedText').find('.commentBox');

        if ($commentBox.is(':hidden')) {
            $commentBox.show();
        }
        else {
            $commentBox.hide();
        }
    });

    /*Online truckers*/
    $('.tabify').tabify();
    $('.module.people-online .mini-filter-menu').tabify();

    /*Mini filter module*/
    var $firstMenuItem = $('.module.people-online .mini-filter-menu li:first');
    if ($firstMenuItem != null && $firstMenuItem[0] != null) {
        $firstMenuItem.addClass('active');
        $($firstMenuItem.find('a').attr('href')).show();
    }

    /* Filter module*/
    $('.filter input[type=checkbox]').each(function () {
        var checkBox = $(this);
        if (checkBox.is(':checked')) {
            checkBox.closest('li').addClass('selected');
        }
    });
    $('.filter input[type=checkbox]:first').each(function () {
        var all = $(this);
        if (all.is(':checked')) {
            all.closest('li').nextAll().addClass('selected');
            all.closest('li').nextAll().each(function () {
                $(this).find('input[type=checkbox]').attr('checked', 'checked');
            });
        }
    });
    $('.filter input[type=checkbox]').bind('click', function (e) {
        var checkBox = $(this);
        var checkBoxName = checkBox.attr('name');
        var firstCheckBox = checkBox.closest('ul').find('input[type=checkbox]:first');
        var firstCheckBoxName = firstCheckBox.attr('name');

        if (checkBox.is(':checked')) {
            checkBox.closest('li').addClass('selected');
        }
        else {
            checkBox.closest('li').removeClass('selected');
        }
        if (firstCheckBoxName == checkBoxName && firstCheckBox.is(':checked')) {
            checkBox.closest('li').nextAll().addClass('selected');
            checkBox.closest('li').nextAll().each(function () {
                $(this).find('input[type=checkbox]').attr('checked', 'checked');
            });
        }

        else if (firstCheckBox.is(':checked')) {
            firstCheckBox.closest('li').removeClass('selected');
            firstCheckBox.removeAttr('checked');
        }
    });


    // Restricted modal
    $('.restricted').live('click', function (e) {
        e.preventDefault();
        var $flashObjects = $('object');
        var url = $(this).attr('href');
        if (url == null || url == 'undefined' || url.substr(0, 10) == 'javascript')
            url = window.location.href;

        jQuery.colorbox({
            href: '/Templates/Handlers/Proxy.ashx?restricted=1&url=' + encodeURIComponent(url),
            onOpen: function () {
                $flashObjects.css('visibility', 'hidden');
            },
            onClosed: function () {
                $flashObjects.css('visibility', 'visible');
            }
        });
    });

    // Add as friend modal
    $('.buttonAddFriend').live('click', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var $flashObjects = $('object');

        jQuery.colorbox({
            href: '/Templates/Handlers/Proxy.ashx?addFriend=1&url=' + encodeURIComponent(url),
            onOpen: function () {
                $flashObjects.css('visibility', 'hidden');
            },
            onClosed: function () {
                $flashObjects.css('visibility', 'visible');
            }
        });

    });

    // Join group modal
    $('.buttonJoinGroup').live('click', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var $flashObjects = $('object');

        jQuery.colorbox({
            href: '/Templates/Handlers/Proxy.ashx?joinGroup=1&url=' + encodeURIComponent(url),
            onOpen: function () {
                $flashObjects.css('visibility', 'hidden');
            },
            onClosed: function () {
                $flashObjects.css('visibility', 'visible');
            }
        });
    });

    // Join group modal

    $('.modal').live('click', function (e) {
        e.preventDefault();
        var url = $(this).attr('href');
        var $flashObjects = $('object');

        jQuery.colorbox({
            href: url,
            onOpen: function () {
                $flashObjects.css('visibility', 'hidden');
            },
            onClosed: function () {
                $flashObjects.css('visibility', 'visible');
            }
        });
    });

    //Submit button/linkbutton on <return>
    var $div = $('.divSubmit');
    $div.keypress(function (e) {
        if (e.which == 13 && e.target.type != 'textarea') {
            var $btn = $(this).find('.btnSubmit');
            if ($btn.type == 'submit') {
                $btn.click();
            }
            else {
                eval($btn.attr('href')); //linkButton
            }
            return false;
        }
    });

    $('.tellafriend').hide();

    //Tell a friend
    $('.tellafriend-toggle').click(function (e) {
        $('.tellafriend').slideToggle('fast');
        return false;
    });

    $('.tellafriend-thanks .enlight').click(function (e) {
        $('.tellafriend-form').slideDown('fast');
        $('.tellafriend-thanks').slideUp('fast');
        return false;
    });



    $('.ajaxLike').live('click', function (e) {
        var $this = $(this);
        var feedSection = $this.closest('.feedText');
        var elementNumLikes = feedSection.find('.numLikes');
        var commentsBox = feedSection.find('.commentBox');
        var likedText = $this.siblings('.buttonLike.liked');
        var originalText = $this.data('text');
        var alternateText = $this.data('alternate');
        $.ajax({
            url: '/Templates/Handlers/Like.ashx',
            data: { content: $(this).data('Entity') },
            cache: false,
            success: function (data) {

                if ($this.html() === alternateText) {
                    $this.html(originalText);
                }
                else {
                    $this.html(alternateText);
                }
                var numLikes = parseInt(data);
                commentsBox.find('li').css('position', 'static');
                if (numLikes === 0) {
                    feedSection.find('.who-likes').addClass('hidden').hide();
                    feedSection.find('.multiple-likers').hide();
                    feedSection.find('.one-liker').hide();
                }
                else {
                    commentsBox.show();
                    if (numLikes == 1) {
                        feedSection.find('.multiple-likers').hide();
                        feedSection.find('.one-liker').show();
                    } else {
                        feedSection.find('.multiple-likers').show();
                        feedSection.find('.one-liker').hide();
                        $(elementNumLikes).html(data);
                    }
                    feedSection.find('.hidden').removeClass('hidden').show();
                }
                commentsBox.find('li').css('position', 'relative');
                var nrOfComments = commentsBox.find('ul.feed > li:not(.commentForm):visible').length;
                if (nrOfComments < 1) {
                    commentsBox.hide();
                }
                //likedText.css('display', 'inline-block');
            }
        });
    });
    
    
    $('.shareScriptGenerator .generator .button-v2').die('click').live('click', function(e) {
    
    	e.preventDefault();
    
    	var $generator 			= $('.shareScriptGenerator .generator');
    	var url 				= $generator.find('[name=url]').val();
    	var share_image 		= $generator.find('[name=share_image]').val();
    	var name 				= $generator.find('[name=name]').val();
    	var description 		= $generator.find('[name=description]').val();
    	var message 			= $generator.find('[name=message]').val();
    	var size				= $generator.find('[name=size]').val();
    	
    	var html 				= '<iframe src="http://'+window.location.hostname+'/share?share_url='+encodeURI(url)+'&share_image='+encodeURI(share_image)+'&name='+encodeURI(name)+'&size='+size+'&description='+encodeURI(description)+'&message='+encodeURI(message)+'" scrolling="no" frameborder="0" style="border:none; overflow:hidden; width:'+size+'px; height:'+size+'px;" allowTransparency="true"></iframe>';
    	
    	$('.shareScriptGenerator .code').text(html);
    	$('.shareScriptGenerator .preview').html(html);
    	
    	$('.shareScriptGenerator .col1').fadeIn();
    	
    	$generator.find('input, textarea, select').unbind('change').bind('change', function(e) {
    		
    		$('.shareScriptGenerator .col1').fadeOut();
    	
    	});
    
    });
    
    
});

function removeFeedItem(id, clientID, removeText) {
    
    $(document).ready(function () {
        $('#wall .viewMoreSection ul.feed > li a.close-button').live('click', function (e) {
            $.ajax({
                url: '/Templates/Handlers/Feed.ashx',
                data: {
                    storyID: id
                },
                cache: false,
                success: function (data) {
                    if (data == 'True') {
                        $('#' + clientID).closest('div').html('<p>' + removeText + '</p>');
                    }
                }
            });
        });
    });
}
