/* IE7 & 8 fix for HTML5 Support */
var html5elmeents = "address|article|aside|audio|canvas|command|datalist|details|dialog|figure|figcaption|footer|header|hgroup|keygen|mark|meter|menu|nav|progress|ruby|section|time|video".split('|');
for (var i = 0; i < html5elmeents.length; i++){
    document.createElement(html5elmeents[i]);
}

/* Globals */
var editProfileMenuValue = 0;

/**
 * jQuery javascript related to designbasen functions.
 * Especially all functions related to lightbox / add/remove from favorites
 * @author Lars Boldt 10/2010 - 11/2010
 */

jQuery.noConflict();

/**
 * Function wrapper to be able to use $ inside functions without messing with Prototype
 */
(function($) {
    /**
     * jQuery UI Dialog wrapper
     * Instead of creating a dialog from scratch we use jQuery UI Dialog which
     * we customize for our use
     */
    $.designbasenDialog = function(options) {
        /* Default options */
        var defaults = {
            title: 'Untitled',
            modal: false,
            resizable: false,
            message: '',
            buttons: {
                Close: function() {
                    $(this).dialog('close');
                }
            }
        };
        /* Override default options */
        var opts = $.extend(defaults, options);

        var dialog = $('<div></div>').attr('id', 'designbasenDialog').attr('title', opts.title).appendTo(document.body);
        $('<p></p>').html(opts.message).appendTo(dialog);
        dialog.dialog({
            modal: opts.modal,
            resizable: opts.resizable,
            buttons: opts.buttons,
            close: function(event, ui) {
                $(dialog).remove();
            }
        });
    };

    /**
     * jQuery getUrlVars function, usage: $.getUrlVars() or $.getUrlVar('name')
     */
    $.extend({
        getUrlVars: function(){
            var vars = [], hash;
            var hashes = window.location.href.slice(window.location.href.indexOf('?') + 1).split('&');
            for(var i = 0; i < hashes.length; i++)
            {
                hash = hashes[i].split('=');
                vars.push(hash[0]);
                vars[hash[0]] = hash[1];
            }
            return vars;
        },
        getUrlVar: function(name){
            return $.getUrlVars()[name];
        }
    });
})(jQuery);

/**
 * Execute this code when document has loaded
 */
jQuery(document).ready(function($) {

    /**
     * Used in Favoritter / Lightboxes
     * toggles active class and slides projects in and out
     */
    $('.lightbox-expand').bind('click', function() {
        var parent = $(this).parent('li');
        // Remove delete btn on images
        parent.find('a.lightbox-items-remove').fadeOut();
        // Remove input box
        parent.find('.lightbox-item-input-header').hide();
        // Remove save link
        parent.find('span.save').hide();
        // Show header span
        parent.find('.lightbox-item-header').show();
        // Show edit link
        parent.find('span.edit').show();

        // Toggle item view and links
        parent.find('.lightbox-expand span.expand').toggle();
        parent.find('.lightbox-expand span.close').toggle();
        parent.toggleClass('lightbox-item-active').find('.lightbox-items').slideToggle();
    });

    /**
     * Used in Favoritter / Lightboxes
     * Edit link actions
     */
    $('span.edit a').bind('click', function() {
        var parent = $(this).parents('li.lightbox-item');

        // Remove header span
        parent.find('.lightbox-item-header').hide();
        // Remove expand list link
        parent.find('.lightbox-expand span.expand').hide();
        // Remove edit link
        $(this).parent('span').hide();

        // Show input box
        parent.find('.lightbox-item-input-header').show();
        // Show save link
        parent.find('span.save').show();
        // Show close list link
        parent.find('.lightbox-expand span.close').show();
        // Show delete btn on images
        parent.find('a.lightbox-items-remove').fadeIn();
        // Expand list and set active class on parent li
        parent.addClass('lightbox-item-active').find('.lightbox-items').slideDown();
    });

    /**
     * Used in Favoritter / Lightboxes
     * Save link actions
     */
    $('span.save a').bind('click', function() {
        var parent = $(this).parents('li.lightbox-item');
        var lbName = parent.find('.lightbox-item-input-header').val();
        var lbId   = parent.find('.lightbox-item-input-header').attr('name');
        $.post('/xmlhttprequest.php?service=lightbox.editlightbox', {
            lightboxID: lbId,
            lightboxName: lbName
        }, function(data) {
            if (data.status == 200) {
                parent.find('span.lightbox-item-header').html(lbName);
                // Remove delete btn on images
                parent.find('a.lightbox-items-remove').fadeOut();
                // Remove input box
                parent.find('.lightbox-item-input-header').hide();
                // Remove save link
                parent.find('span.save').hide();
                // Show header span
                parent.find('.lightbox-item-header').show();
                // Show edit link
                parent.find('span.edit').show();
            }
            var buttons = {};
            if (typeof(data.closeBtnText) != 'undefined') {
                buttons[data.closeBtnText] = function() {
                    $(this).dialog('close');
                }
            }
            $.designbasenDialog({
                title: data.title,
                message: data.message,
                buttons: buttons
            });
            if (typeof(data.closeBtnText) == 'undefined') {
                $('.ui-dialog').fadeTo(1000).fadeOut(800, function() {
                    $('#designbasenDialog').dialog('close');
                });
            }
        }, 'json');
    });

    /**
     * Remove item from lightbox
     * Posts form through xmlhttprequest and fades out element if success on removal
     * Also updates the item count on lightbox
     */
    $('.lightbox-items-remove').bind('click', function() {
        var element = $(this);
        $.post('/xmlhttprequest.php?service=lightbox.getremoveitemsdialogdata', {}, function(data) {
            var buttons = {};
            buttons[data.deleteBtnText] = function() {
                $(this).dialog('close');
                $.post('/xmlhttprequest.php?service=lightbox.removeentity', {
                    entityUniqueID: element.attr('id'),
                    lightboxID: element.attr('rel')
                }, function(data) {
                    if (data == 200) {
                        element.parents('li:first').fadeOut(500, function() {
                            element.parents('li.lightbox-item').find('span.lightbox-item-count').html(parseInt(element.parents('li.lightbox-item').find('span.lightbox-item-count').html())-1);
                        });
                    } else {
                        alert('Error');
                    }
                });
            };
            buttons[data.closeBtnText] = function() {
                $(this).dialog('close');
            }
            $.designbasenDialog({
                title: data.title,
                message: data.message,
                buttons: buttons
            });
        }, 'json');
    });

    /**
     * Remove lightboxes
     */
    $('#remove-lightboxes').bind('submit', function() {
        if ($(this).serialize().length > 0) {
            $.post('/xmlhttprequest.php?service=lightbox.removelightbox', {
                lightboxID: $(this).serialize()
            }, function(data) {
                var arr = data.split(',');
                for (n in arr) {
                    $('#lightbox-' + arr[n]).fadeOut(500, function() {
                        $(this).remove();
                        $('ul.lightbox-list').children('li').each(function(i, e) {
                            var newClass = (i % 2) ? 'lightbox-item-even' : 'lightbox-item-odd';
                            $(this).removeClass('lightbox-item-odd').removeClass('lightbox-item-even').addClass(newClass);
                        });
                    });
                }
            });
        }

        return false;
    });

    /**
     * Remove lightboxes confirm dialog
     */
    $('#lightbox-items-remove-selected').bind('click', function() {
        $.post('/xmlhttprequest.php?service=lightbox.getremovelightboxdialogdata', {}, function(data) {
            var buttons = {};
            buttons[data.deleteBtnText] = function() {
                $('#remove-lightboxes').submit();
                $(this).dialog('close');
            };
            buttons[data.closeBtnText] = function() {
                $(this).dialog('close');
            };
            $.designbasenDialog({
                title: data.title,
                message: data.message,
                buttons: buttons
            });
        }, 'json');
    });

    /**
     * Add entity to lightbox
     */
    $('.addtolightboxlink').bind('click', function() {
        var element = $(this);
        $.post('/xmlhttprequest.php?service=lightbox.getaddlightboxdialogdata', {}, function(data) {
            // data is a JSON object which include data and different labels, that way labels can be customized in corepublish
            var buttons = {};
            if (data.status == 200) {
                // We'll get the lightbox options as JSON so we'll loop through and add the html
                var lightboxOptions = '';
                for (n in data['lightboxes']) {
                    lightboxOptions += '<option value="' + n + '">' + data['lightboxes'][n] + '</option>';
                }
                // We'll get button labels as JSON so we need to specify these outside the dialog option scope
                buttons[data.saveBtnText] = function() {
                    // get id and name before dialog is destroyed
                    var userLightboxID = $('#userLightboxID').val();
                    var newLightboxname = $('#newLightbox').val();
                    // close current dialog
                    $(this).dialog('close');
                    // Post the actual add entity form to server, the previous call was only to populate dialog with labels and user choices
                    $.post('/xmlhttprequest.php?service=lightbox.addentity', {
                        entityUniqueID: element.attr('id'),
                        lightboxID: userLightboxID,
                        newLightbox: newLightboxname
                    }, function(data) {
                        // data is a JSON object which include data and different labels, that way labels can be customized in corepublish
                        var button = {};
                        button[data.closeBtnText] = function() {
                            $(this).dialog('close');
                        };
                        // pop new dialog with server response
                        $.designbasenDialog({
                            title: data.title,
                            message: data.message,
                            buttons: button
                        });
                    }, 'json');
                };
                buttons[data.closeBtnText] = function() {
                    $(this).dialog('close');
                };
                // pop new dialog with server response
                $.designbasenDialog({
                    title: data.title,
                    message: '<label for="userLightboxID">' + data.selectLabel + '</label><select id="userLightboxID" name="userLightboxID">' + lightboxOptions + '</select><label for="newLightbox">' + data.newLightboxLabel + '</label><input id="newLightbox" name="newLightbox" type="text" />',
                    buttons: buttons
                });
            } else {
                buttons[data.registerBtnText] = function() {
                    window.location=data.registerBtnUrl;
                };
                // pop new dialog with server response
                $.designbasenDialog({
                    title: data.title,
                    message: data.message,
                    buttons: buttons
                });
            }
        }, 'json');
    });

    /**
     * Dropdown menu
     * Uses hoverIntent plugin to delay mouseover/mouseout functions
     */
    var ddTimer;
    var mouseOver = function() {
        clearTimeout(ddTimer);
        $('#ddusermenu').slideDown(400);
    //$('#ddusername').css('background-image', 'url(\'/themes/designbasen/images/placeholder-header-bg-r.png\')');
    }
    var mouseOut = function() {
        clearTimeout(ddTimer);
        ddTimer = setTimeout(function() {
            $('#ddusermenu').slideUp(300);
        //$('#ddusername').css('background-image', '');
        }, 1000);
    }
    $('#ddusername').hoverIntent(mouseOver, mouseOut);
    $('#ddusermenu').hoverIntent(function() {
        clearTimeout(ddTimer);
    }, mouseOut);

    /**
     * Statistics, toggle project list
     */
    $('select#listview').bind('change', function() {
        switch ($(this).val()) {
            case 'topten':
                $('dl.hidden').hide();
                break;
            case 'all':
                $('dl.hidden').show();
        }
    });
    $('select#timespan').bind('change', function() {
        switch ($(this).val()) {
            case 'today':
                $('div.project-list-count_total').hide();
                $('div.project-list-count_week').hide();
                $('div.project-list-count_month').hide();

                $('div.project-list-count_today').show();
                break;
            case 'week':
                $('div.project-list-count_total').hide();
                $('div.project-list-count_today').hide();
                $('div.project-list-count_month').hide();

                $('div.project-list-count_week').show();
                break;
            case 'month':
                $('div.project-list-count_total').hide();
                $('div.project-list-count_week').hide();
                $('div.project-list-count_today').hide();

                $('div.project-list-count_month').show();
                break;
            case 'total':
                $('div.project-list-count_today').hide();
                $('div.project-list-count_week').hide();
                $('div.project-list-count_month').hide();

                $('div.project-list-count_total').show();
                break;
        }
    });

    /**
     * Project List SLIDER
     */
    var scrollPane = $('#project-articlelist-wrapper'), scrollContent = $('#project-articlelist');
    scrollContent.css('width', ((scrollContent.find('li').length*189)-5) + 'px');
    $('ul.block-of.projects').css('width', ((scrollContent.find('li').length*189)-5) + 'px');
    if (scrollContent.find('li').length <= 5) {
        $('.project-slider-wrapper').hide();
    } else {
        var scrollbar = $('#project-slider').slider({
            slide: function( event, ui ) {
                if ( (scrollContent.width()) > scrollPane.width() ) {
                    scrollContent.css( "margin-left", Math.round(
                        ui.value / 100 * ( scrollPane.width() - (scrollContent.width()) )
                        ) + "px" );
                } else {
                    scrollContent.css( "margin-left", 0 );
                }
            }
        });
        scrollbar.find( ".ui-slider-handle" ).append( '<span class="ui-slider-grip"></span>' ).wrap('<div class="slide-wrap"></div>').parent();
        var handlebar = scrollbar.find( ".ui-slider-handle:first" );
        var width = (scrollContent.width() <= 945) ? 868 : 868*Math.pow(0.89, (scrollContent.find('li').length-5));
        width = (width < 70) ? 70 : width;
        width = (width > 868) ? 868 : width;
        handlebar.css('width', width);
        $('.slide-wrap').css('width', 868-handlebar.width() + 'px').css('position', 'relative');
    }
    var sliderIsScrolling = false;
    $('#project-slider-left-btn').bind('click', function() {
        if (! sliderIsScrolling) {
            sliderIsScrolling = true;
            var currentMargin, newMargin;
            currentMargin = parseInt(scrollContent.css('margin-left'));
            newMargin = currentMargin+945;
            newMargin = (newMargin > 0) ? 0 : newMargin;
            calculateHandlePosition(newMargin);
            scrollContent.animate({
                marginLeft: newMargin + 'px'
            }, 700, function() {
                sliderIsScrolling = false;
            });
        }
    });
    $('#project-slider-right-btn').bind('click', function() {
        if (! sliderIsScrolling) {
            sliderIsScrolling = true;
            var currentMargin, newMargin, totalWidth;
            totalWidth = -scrollContent.width();
            currentMargin = parseInt(scrollContent.css('margin-left'));
            newMargin = currentMargin-945;
            newMargin = (newMargin < (totalWidth+940)) ? (totalWidth+940) : newMargin;
            calculateHandlePosition(newMargin);
            scrollContent.animate({
                marginLeft: newMargin + 'px'
            }, 700, function() {
                sliderIsScrolling = false;
            });
        }
    });

    function calculateHandlePosition(newMargin) {
        newMargin = Math.abs(newMargin);
        var handleWidth = handlebar.width();
        var scrollWidth = 868;
        var handleScrollArea = scrollWidth - handleWidth;
        var scrollArea = scrollContent.width()-945;
        var moveRatio = scrollArea / handleScrollArea;
        var newHandleMargin = newMargin / moveRatio;
        var newHandleLeft = Math.floor(newHandleMargin / handleScrollArea * 100);
        handlebar.animate({
            left: +newHandleLeft + '%'
        }, 700);
    }

    /**
     * Edit profile - Posten zipcode / county lookup
     * Intended to get this directly from fraktguiden @ bring.no, but since we
     * needed counties we had to make a custom solution
     */
    $('#ep-zipcode').bind('keyup', function() {
        if ($(this).val().length == 4) {
            $('.ep-zipcode-loader').html('<img src="/themes/designbasen/images/ajax-loader.gif" alt="loader" width="16" height="16" /> Søker...');
            $.post('/xmlhttprequest.php?service=designbasen.editprofile.zipcode', {
                zipcode: $(this).val()
            }, function(data){
                if (typeof(data.area) != 'undefined') {
                    $('.ep-area-text').html(data.area);
                    $('.ep-county-text').html(data.county);
                } else {
                    $('.ep-area-text').html(data.error);
                    $('.ep-county-text').html('');
                }
                $('.ep-zipcode-loader').html('');
            }, 'json');
        } else {
            $('.ep-area-text').html('');
            $('.ep-county-text').html('');
        }
    });
    $('#ep-zipcode').keyup();

    /**
     * Edit profile, branch fold/expand
     */
    $('.branches li a').bind('click', function() {
        $(this).parent('li').children('.branch-childs').slideToggle();
        $(this).toggleClass('branch-menu-collapsed').toggleClass('branch-menu-expanded');
    });
    
    /**
     * Edit profile, menu tabs
     */    
    $('.edit-profile ol.tabs').children('li.active').children('ul').show();
    $('.edit-profile ol.tabs').children('li:not(:first)').hide();
    $('.Firmaprofil-2 li a').bind('click', function() {
        $('.Firmaprofil-2 li a').css('background-color', '#dcdcdc');
        $(this).css('background-color', '#c4c4c4');
        var menuIndex = $(this).parent('li').index();
        $('.edit-profile ol.tabs').children().each(function(i, e) {
            if (i == menuIndex) {
                editProfileMenuValue = i;
                $('.edit-profile ol.tabs').children().hide();
                $(this).show();
                
                if (editProfileMenuValue > 0) {
                    $('.edit-profile .toolbar .prev a').show();
                } else {
                    $('.edit-profile .toolbar .prev a').hide();
                }
                if (editProfileMenuValue >= 8) {
                    $('.edit-profile .toolbar .next a').hide();
                } else {
                    $('.edit-profile .toolbar .next a').show();
                }
                
                return false;
            }
        });
        return false;
    });
    if ($.getUrlVar('tab') > 0 && $.getUrlVar('tab') < 10) {
        $('.Firmaprofil-2 li').each(function(i, e) {
            if ((i+1) == $.getUrlVar('tab')) {
                editProfileMenuValue = i+1;
                $(this).children('a:first').click();
                return false;
            }
        });
    }    

    /**
     * Edit profile, suggest designbasen url based on company name
     */
    $('#companyname').bind('blur', function() {
        var durl = $(this).attr('value').toLowerCase();
        durl = durl.replace(/ /g, '-');
        durl = durl.replace(/ø/gi, 'o');
        durl = durl.replace(/æ/gi, 'ae');
        durl = durl.replace(/å/gi, 'a');
        $('#durl').html('designbasen.no/' + durl);
    });

    /**
     * Edit profile, textarea stroke counter
     */
    $('textarea.tweet-strokes').bind('keydown keyup blur focus click mouseover mouseout', function() {
        var tweet = $(this).val().length;
        if (tweet > 140) {
            tweet = 140;
            $(this).val($(this).val().substr(0, 140));
        }
        $('span.tweet-strokes').html(140-tweet);
    });
    if ($('textarea.tweet-strokes').length) {
        $('span.tweet-strokes').html(140-$('textarea.tweet-strokes').val().length);
    }

    /**
     * Edit profile, description textarea stroke counter
     */
    $('textarea.desc-strokes').bind('keydown keyup blur focus click mouseover mouseout', function() {
        var desc = $(this).val().length;
        $('span.desc-strokes').html(1000-desc);
    });
    if ($('textarea.desc-strokes').length) {
        $('span.desc-strokes').html(1000-$('textarea.desc-strokes').val().length);
    }

    /**
     * Designbasen menu, collapse / expand submenus
     */
    $('.vertical-menu ul:first').children('li').each(function(i, e) {
        if ($(this).hasClass('active') || $(this).hasClass('main-active')) {
            if ($(this).has('ul').length) {
                $(this).children('a:first').addClass('expanded');
            }
        } else {
            if ($(this).has('ul').length) {
                $(this).children('a:first').addClass('collapsed');
                $(this).children('ul:first').hide();
            }
        }
        if ($(this).has('ul').length) {
            $(this).children('a:first').bind('click', function() {
                if ($(this).hasClass('collapsed')) {
                    $(this).removeClass('collapsed').addClass('expanded');
                    $(this).parent('li').children('ul').slideDown();
                } else {
                    $(this).removeClass('expanded').addClass('collapsed');
                    $(this).parent('li').children('ul').slideUp();
                }

                return false;
            });
        }
    });
    
    /**
     * Edit profile - Prev/Next buttons
     */
    $('.edit-profile .toolbar .prev a').bind('click', function() {
        var newVal = editProfileMenuValue-1;
        newVal = (newVal < 0) ? 0 : newVal;
        $('.Firmaprofil-2 li').each(function(i, e) {
            if (i == newVal) {                
                saveForm($(this).children('a:first'), newVal);                                
                return false;
            }
        });
    });
    $('.edit-profile .toolbar .next a').bind('click', function() {
        var newVal = $('.edit-profile ol.tabs').children('li').length;
        newVal = ((editProfileMenuValue+1) > newVal) ? newVal : (editProfileMenuValue+1);
        $('.Firmaprofil-2 li').each(function(i, e) {
            if (i == newVal) {
                saveForm($(this).children('a:first'), newVal);                               
                return false;
            }
        });
    });
    if (editProfileMenuValue <= 0) {
        $('.edit-profile .toolbar .prev a').hide();
    } else if (editProfileMenuValue >= 9) {
        $('.edit-profile .toolbar .next a').hide();
    }

    /**
     * Edit profile form saver
     */
    $('.edit-profile .toolbar li.save a').bind('click', function() {
        saveForm();
    });    

    $('form.projectform').ajaxForm({
        target: $(this).attr('action'),
        dataType: 'json',
        success: function(data) {
            if (data != null && typeof(data) == 'object') {
                for (n in data) {
                    switch (n) {
                        case 'image1':
                            alert('Bilde 1: ' + data[n]);
                            break;
                        case 'image2':
                            alert('Bilde 2: ' + data[n]);
                            break;
                        case 'image3':
                            alert('Bilde 3: ' + data[n]);
                            break;
                        case 'image4':
                            alert('Bilde 4: ' + data[n]);
                            break;
                        case 'error':
                            alert(data[n]);
                            break;
                        case 'url':
                            window.location = data[n].replace(/&amp;/, '&');
                            break;
                    }
                }
            }
        }
    });
    $('div.btns a.projectsave').bind('click', function() {
        if (! formSubmitInProgress) {
            formSubmitInProgress = true;
            $(this).html('Vennligst vent...');
            $('div.btns a.cancel').hide();
            $(this).parents('form.projectform').submit();
        }
    });

    /**
     * Edit profile new industry
     */
    $('a#newIndustry').bind('click', function() {
        $('ol.industries').append($('#industries-dummy').html());
        $('ol.industries').find(':input[name=dummy-industry]').attr('name', 'industry[]');

        $('ol.industries').children('li').removeClass('last');
        $('ol.industries').children('li:last').addClass('last');

        bindEditProfileEvents();

        $('ol.industries').children('li:last').find('img.edit').click();
        var lastElementPos = $('ol.industries').children('li:last').position();
        $(document).scrollTop(lastElementPos.top);
    });

    /**
     * Edit profile new client
     */
    $('a#newClient').bind('click', function() {
        $('ol.clients').append($('#clients-dummy').html());
        $('ol.clients').find(':input[name=dummy-client]').attr('name', 'client[]');
        $('ol.clients').find(':input[name=dummy-clienturl]').attr('name', 'clienturl[]');

        $('ol.clients').children('li').removeClass('last');
        $('ol.clients').children('li:last').addClass('last');

        bindEditProfileEvents();

        $('ol.clients').children('li:last').find('img.edit').click();
        var lastElementPos = $('ol.clients').children('li:last').position();
        $(document).scrollTop(lastElementPos.top);
    });

    /**
     * Edit profile new recommendation
     */
    $('a#newRecommendation').bind('click', function() {
        $('ol.recommendations').append($('#recommendations-dummy').html());
        $('ol.recommendations').find(':input[name=dummy-name]').attr('name', 'name[]');
        $('ol.recommendations').find(':input[name=dummy-position]').attr('name', 'position[]');
        $('ol.recommendations').find(':input[name=dummy-company]').attr('name', 'company[]');

        $('ol.recommendations').children('li').removeClass('last');
        $('ol.recommendations').children('li:last').addClass('last');

        bindEditProfileEvents();

        $('ol.recommendations').children('li:last').find('img.edit').click();
        var lastElementPos = $('ol.recommendations').children('li:last').position();
        $(document).scrollTop(lastElementPos.top);
    });

    /**
     * Edit profile new award
     */
    $('a#newAward').bind('click', function() {
        $('ol.awards').append($('#awards-dummy').html());
        $('ol.awards').find(':input[name=dummy-award]').attr('name', 'award[]');
        $('ol.awards').find(':input[name=dummy-url]').attr('name', 'url[]');

        $('ol.awards').children('li').removeClass('last');
        $('ol.awards').children('li:last').addClass('last');

        bindEditProfileEvents();

        $('ol.awards').children('li:last').find('img.edit').click();
        var lastElementPos = $('ol.awards').children('li:last').position();
        $(document).scrollTop(lastElementPos.top);
    });

    /**
     * Edit profile new project/job
     */
    $('a#newProject').bind('click', function() {
        $.post('/xmlhttprequest.php?service=designbasen.editprofile.form', {
            tab: 'projectnew'
        }, function(data) {
            if (data != null && typeof(data) == 'object' && typeof(data.error) != 'undefined' && data.error.length) {
                alert(data.error);
            } else if (data != null && typeof(data) == 'object' && typeof(data.url) != 'undefined' && data.url.length) {
                window.location = data.url;
            } else {
                alert('Return url not received, please refresh page manually.');
            }
        }, 'json');
    });

    /**
     * Search filter collapse/expand
     */
    $('a.countyfilterlink').bind('click', function() {
        if ($(this).hasClass('filter-collapse')) {
            $(this).removeClass('filter-collapse');
            $('ul.countyfilterlist').hide();
        } else {
            $('ul.countyfilterlist').show();
            $(this).addClass('filter-collapse');
        }
    });
    $('ul.filterExpand li a').bind('click', function() {
        if ($(this).hasClass('filter-collapse')) {
            $(this).removeClass('filter-collapse');
            $(this).parent('li').children('ul:first').hide();
        } else {
            $(this).parent('li').children('ul:first').show();
            $(this).addClass('filter-collapse');
        }
    });

    /**
     * Project page - Advanced List Rotator gallery
     */
    $('.project-gallery').advListRotator({
        effect: 'fade',
        effectTimer: 2000,
        activeItemClass: 'alrActive',
        helper: $('.project-gallery-thumbs'),
        unevenHeightsFix: true
    });

    /**
     * Project page - Show/hide overflow description
     */
    $('#project-description-limit-expand').bind('click', function() {
        if ($('p.project-description-limit').css('height') == 'auto') {
            $('p.project-description-limit').css('height', '393px');
            $(this).html('Les mer [+]');
        } else {
            $('p.project-description-limit').css('height', 'auto');
            $(this).html('Les mer [-]');
        }
    });

    /**
     * Contact info company page, move org.nr to 2nd position in ul
     */
    $('#con-info li:first').after($('#con-org'));   

    /**
     * Bind events, see function below
     */
    bindEditProfileEvents();

    /**
     * Frontpage block-of-profiles animation
     */
    //animateFrontpageProfiles(0, $('div.bop-front').find('ul.block-of-profiles').length);
    
    /**
     * Trigger open and scroll down to newest added project in profile edit
     */
    var lastElementPos;
    if (typeof($.getUrlVar('nj')) != 'undefined') {
        $('ol.projects').children('li:last').find('img.edit').click();
        lastElementPos = $('ol.projects').children('li:last').position();
        $(document).scrollTop(lastElementPos.top);
    }
    if (typeof($.getUrlVar('ej')) != 'undefined') {
        $('ol.projects').children('li#p_' + $.getUrlVar('ej')).find('img.edit').click();
        lastElementPos = $('ol.projects').children('li#p_' + $.getUrlVar('ej')).position();
        $(document).scrollTop(lastElementPos.top);
    }
    
    /**
     * slideToggle competancies search box
     */
    $('.db-search td.competancy a.competancy-expand').bind('click', function() {
        $(this).parent().find('ul:first').slideToggle(250);
        $(this).parent().toggleClass('expanded');
        return false;
    });
    $('.db-search .location li a.location-expand').bind('click', function() {
        $(this).parent().find('ul:first').slideToggle(250);
        $(this).parent().toggleClass('expanded');
        return false;
    });
    $('.db-search .search-expand').bind('click', function() {
        $(this).parent().parent().find('form:first').slideToggle(250);
        $(this).parent().toggleClass('expanded');
        return false;
    });
    $('.db-search input.search_sbmt').bind('click', function() {
        $(this).attr('src', '/themes/designbasen/images_db/search_btn_press.jpg');
    })
    $('.db-search input.search_sbmt').bind('mouseover', function() {
        $(this).attr('src', '/themes/designbasen/images_db/search_btn_hover.jpg');
    })
    $('.db-search input.search_sbmt').bind('mouseout', function() {
        $(this).attr('src', '/themes/designbasen/images_db/search_btn.jpg');
    })
    $('div.db-search .freetext .search').bind('click', function() {
        $('div.content div.db-search .freetext input:first').focus();
    });
    
    /* Last profiles default image */
    $('ul.block-of-profiles div.imagediv a').each(function() {
        if ($(this).find('img').length <= 0) {
            $(this).append('<img src="/themes/designbasen/images_db/default_bilde.jpg" alt="default" />');
        }
    });
});

/**
 * Since new items in Edit profile is added by javascript and not saved
 * before the user actually clicks "Save" we need to bind some standard
 * events to the newly added DOM elements so the user can sort/edit/delete
 * before they save.
 */
function bindEditProfileEvents() {
    (function($) {
        /**
         * Edit profile, toggle toolbar
         */
        $('.sortable a').bind('mouseover', function() {
            $(this).children('span.edit-toolbar').show();
        });
        $('.sortable a').bind('mouseout', function() {
            $(this).children('span.edit-toolbar').hide();
        });

        /**
         * Edit profile sort
         */
        $('.edit-profile-sort').sortable({
            items: 'li.sortable',
            handle: 'img.sort',
            axis: 'y',
            containment: 'parent',
            tolerance: 'pointer',
            stop: function() {
                $(this).children('li').removeClass('last');
                $(this).children('li:last').addClass('last');
            }
        });

        /**
         * Edit profile, sort delete
         */
        $('.edit-profile-sort img.delete').bind('click', function() {
            $(this).parents('li.sortable').remove();
        });

        /**
         * Edit profile, sort edit
         */
        $('.edit-profile-sort img.edit').bind('click', function() {
            $(this).parents('li.sortable').addClass('edit').children('div.edit').show();
            $(this).parents('a:first').hide();
        });
        $('.edit-profile-sort div.btns a.cancel').bind('click', function() {
            $(this).parents('li.sortable').removeClass('edit').children('div.edit').hide();
            $(this).parents('li:first').children('a:first').show();
        });
        $('.edit-profile-sort div.btns a.save').bind('click', function() {
            $(this).parents('li.sortable').removeClass('edit').children('div.edit').hide();
            $(this).parents('li:first').children('a:first').show().children('span.text').html($(this).parents('div.edit').children('input').val());
        });
    })(jQuery);
}

/**
 * Check if profile has been activated and update text accordingly
 */
function refreshProfileStatus() {
    (function($) {
        $.post('/xmlhttprequest.php?service=designbasen.editprofile.form', {
            tab: 'profilestatus'
        }, function(response) {
            if (typeof(response.status) != 'undefined' && response.status.length) {
                $('#profile-active').html(response.status);
            }
        }, 'json');
    })(jQuery);
}

/**
 * Designbasen frontpage, block-of-profiles (bop-front) animations
 */
function animateFrontpageProfiles(c, m) {
    (function($) {
        if (m > 1) {
            var bop = $('div.bop-front');
            var blocks = $('div.bop-front').find('ul.block-of-profiles');
            var next = ((c+1) >= m) ? 0 : c+1;
            bop.css('position', 'relative').css('height', '300px').css('overflow', 'hidden');
            blocks.each(function(index, element) {
                $(element).hide();
                if (index == c) {
                    $(element).children('li').each(function(i, e) {
                        $(e).css('float', 'none').css('position', 'absolute').css('margin-right', 0).css('left', i*189).css('top', 0);
                    });
                    $(element).css('height', '300px').show();
                    $(element).children('li').each(function(i, e) {
                        setTimeout(function() {
                            $(e).animate({
                                top: '301px'
                            }, 1500);
                        }, 7000+(i*100));
                    });
                } else if (index == next) {
                    $(element).children('li').each(function(i, e) {
                        $(e).css('left', i*189);
                    });
                    $(element).children('li').stop().css('float', 'none').css('position', 'absolute').css('margin-right', 0).css('top', '-300px');
                    $(element).css('height', '300px').show();
                    $(element).children('li').each(function(i, e) {
                        setTimeout(function() {
                            $(e).animate({
                                top: 0
                            }, 1500, function() {
                                if (i == ($(element).children('li').length-1)) {
                                    animateFrontpageProfiles(next, m);
                                }
                            });
                        }, 7000+(i*100));
                    });
                }
            });
        }
    })(jQuery);
}

var formSubmitInProgress = false;
function saveForm(obj, menuId) {
    (function($) {
        $('.edit-profile ol.tabs').children('li').each(function(i, e) {
            if ($(this).css('display') != 'none') {
                /**
                 * Normal submit
                 */
                if ($(this).children('form').length) {
                    if ($(this).children('form').attr('id') == 'about') {
                        if (! formSubmitInProgress) {
                            formSubmitInProgress = true;
                            saveAjaxForm(obj);
                        }
                    } else {
                        if (! formSubmitInProgress) {
                            formSubmitInProgress = true;
                            $('div.btns a.cancel').hide();
                            $('.toolbar .saving').show();
                            $.post($(this).children('form').attr('action'), $(this).children('form').serialize(), function(data) {
                                $('.toolbar .saving').hide();
                                $('div.btns a.cancel').show();
                                formSubmitInProgress = false;
                                var formHasErrors = false;
                                if (data != null && typeof(data) == 'object') {
                                    for (n in data) {
                                        switch (n) {
                                            case 'error':
                                                alert(data[n]);
                                                formHasErrors = true;
                                                break;
                                            default:
                                                if (n.indexOf('msg') >= 0 && data[n].length > 0) {
                                                    formHasErrors = true;
                                                }
                                                $('#' + n).html(data[n]);
                                        }
                                    }
                                }
                                if (!formHasErrors) {
                                    refreshProfileStatus();
                                    if (typeof(obj) != 'undefined') {
                                        obj.click();
                                        if (typeof(menuId) != 'undefined') {
                                            editProfileMenuValue = menuId;
                                            if (menuId < 8) {
                                                $('.edit-profile .toolbar .next a').show();
                                            } else {
                                                $('.edit-profile .toolbar .next a').hide();
                                            }
                                            if (menuId <= 0) {
                                                $('.edit-profile .toolbar .prev a').hide();
                                            } else {
                                                $('.edit-profile .toolbar .prev a').show();
                                            }
                                        }
                                    }
                                }
                            }, 'json');
                        }
                    }
                    return false;
                /**
                 * If tab 8 (9), it's project sort, do special magic
                 */
                } else if (i == 8) {
                    if (! formSubmitInProgress) {
                        formSubmitInProgress = true;
                        var qStr = $('ol.projects').sortable('serialize');
                        qStr += '&tab=projectsort';
                        $('.toolbar .saving').show();
                        $('div.btns a.cancel').hide();
                        $.post('/xmlhttprequest.php?service=designbasen.editprofile.form', qStr, function(data) {
                            $('.toolbar .saving').hide();
                            $('div.btns a.cancel').show();
                            formSubmitInProgress = false;
                            if (typeof(obj) != 'undefined') {
                                obj.click();
                            }
                            if (data != null && typeof(data) == 'object' && typeof(data.error) != 'undefined' && data.error.length) {
                                alert(data.error);
                            }
                        }, 'json');
                    }
                } else {
                    alert('missing form');
                }
            }
        });
    })(jQuery);
}

function saveAjaxForm(obj) {
    (function($) {
        /**
         * About ajax form (file) submit
         */
        $('form#about').ajaxForm({
            target: $(this).attr('action'),
            dataType: 'json',
            beforeSubmit: function() {
                $('div.btns a.cancel').hide();
                $('.toolbar .saving').show();
            },
            success: function(data) {
                formSubmitInProgress = false;
                $('div.btns a.cancel').show();
                $('.toolbar .saving').hide();
                $('input#logo').val('');
                if (data != null && typeof(data) == 'object' && typeof(data.logo) != 'undefined' && data.logo.length) {
                    $('#logo-img').fadeOut(500);
                    $('#logo-img').attr('src', data.logo);
                    $('#logo-img').fadeIn(500, function() {
                        if (typeof(obj) != 'undefined') {
                            obj.click();
                        }
                        refreshProfileStatus();
                    });
                } else if (data != null && typeof(data) == 'object' && typeof(data.logo_error) != 'undefined' && data.logo_error.length) {
                    alert(data.logo_error);
                } else {
                    if (typeof(obj) != 'undefined') {
                        obj.click();
                    }
                    refreshProfileStatus();
                }
            }
        });
        $('form#about').submit();
    })(jQuery);
}
