﻿jQuery(document).ready(function($){
    // placeholder in textfields
    $('input[type=text].toggle_value').focus(function(){
        if ($(this).val().length > 0) 
            $(this).data('initValue', $(this).val()).val('');
    }).blur(function(){
        if ($(this).val().length == 0 && typeof($(this).data('initValue')) != 'undefined')
            $(this).val( $(this).data('initValue') );
    });

    // login links
    $('a.force_login').click(function(){
        $.scrollTo('#login', 1000);
        return false;
    });
    
    $('#alert').jqm({
						overlay: 0, 
						modal: false, 
						trigger: false, 
						onShow: function(hash){
							if (hash.w.data('autoClose') != undefined) {
								setTimeout(function(){
										// re-check fadeout, cause there might be
										// another alert displayed now (3000ms after function invoked)
										if (hash.w.data('autoClose') != undefined)
											hash.w.jqmHide().removeData('autoClose');
								}, 3000);
							}

							hash.w.fadeIn('fast');
						},
						onHide: function(hash){ 
							hash.w.fadeOut('fast'); 
							if (hash.o) hash.o.remove(); // overlay
							hash.w.removeData('autoClose');
						}
					});

    $('#confirm').jqm({
						overlay: 0, 
						modal: true, 
						trigger: false, 
						onShow: function(hash){ hash.w.fadeIn('fast'); },
						onHide: function(hash){ 
							hash.w.fadeOut('fast'); 
							if (hash.o) hash.o.remove();
						}
					});
					
	// Infield Labels on login
	$("#header_usermenu .login .login_field label").inFieldLabels({ fadeOpacity:0.3, fadeDuration:300 });
});

(function($){
    $.fn.scrollTo = function(elem, duration) {
        var d = (duration == undefined || isNaN(duration)) ? 'slow' : duration;
        var p = (typeof(elem) == 'string') ? $(elem) : elem;
        if (p.length == 0) p = 0;
        else p = p.position().top;
        
        $('html, body').animate({scrollTop: p}, d);
        return elem;
    };

    /**
     * Toggle visibility of block content - inserts Skjul / Vis links in the block header
     * elem = element with .block_header and .block_content (typically a div.block)
     * options {type: 'text/image', onVisible: 'hide text / hide image path', onHidden: 'show text / show image path', appendTo: 'append anchor to given element (selector)' }
     */
    $.fn.toggleContent = function(options) {
        var defaults = {
            type: 'text',
            onVisible: '(skjul)',
            onHidden: '(vis)',
            appendTo: ''
        };
        var opts = $.extend(defaults, options); // merge default with options
        
        var $this = $(this);
        var content = $this.children('.block_content');
        var header = $this.children('.block_header:first');
        
        // render toggle link
        var toggleAnchor = $('<a href="#" style="margin-left:10px;"></a>')
                                    .data('toggleContent', opts)
                                    .click(function(){                                        
                                        var $anchor = $(this);

                                        if (content.is(':visible'))
                                            content.slideUp('fast', function(){
                                                // alter anchor content
                                                renderInnerContent(content, $anchor, opts);                                                
                                            });
                                        else
                                            content.slideDown('fast', function(){
                                                // alter anchor content
                                                renderInnerContent(content, $anchor, opts);
                                            });
                                        
                                        return false;
                                    });
        
        // create and insert anchor
        renderInnerContent(content, toggleAnchor, opts);  
        
        // insert anchor into a specific place in the header?
        if (opts.appendTo.length > 0) {
            var appendToElem = header.children(opts.appendTo);
            if (appendToElem.length > 0) appendToElem.append( toggleAnchor );
        }
        // nope, append directly into header
        else
            header.append( toggleAnchor );
        
        return $this;
    };
    
    // helper function to create / alter inner content of the toggle anchor
    function renderInnerContent($content, $toggleAnchor, opts) {
        var anchorInner = $content.is(':visible') ? opts.onVisible : opts.onHidden;
        if (opts.type == 'image') {
            var img = $toggleAnchor.children('img:first');
            // need to insert image in this anchor?
            if (img.length == 0) {
                img = $('<img src=""/>');
                $toggleAnchor.append(img);
            }
            
            img.attr('src', anchorInner);
        } 
        else 
            $toggleAnchor.text( anchorInner );
    };
    
    /**
     * Insert content at caret position (converted to jquery function)
     * @link http://alexking.org/blog/2003/06/02/inserting-at-the-cursor-using-javascript
     */
    $.fn.insertAtCaret = function (myValue) {
            return this.each(function(){
                    //IE support
                    if (document.selection) {
                            this.focus();
                            sel = document.selection.createRange();
                            sel.text = myValue;
                            this.focus();
                    }
                    //MOZILLA/NETSCAPE support
                    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();
                    }
            });
    };
    
    /**
     * Relate tab to content (id) specified in the tab's rel-attr.
     * Options: {
     *              selectFirstTab: true - whether or not to select the first tab when document is ready 
     *              selectedClass: 'current' - class to add when tab is selected
     *          }
     */
    $.fn.relateTab = function(options){
        var defaults = { selectFirstTab: true, selectedClass: 'current' };
        var opts = $.extend(defaults, options);        
        
        return $(this).each(function(index){
            var $this = $(this);
            var content = $( $this.attr('rel') );
            var classSelector = '.' + opts.selectedClass;
            
            // attach click handler
            $this.click(function(){
                if ($this.is(classSelector) || content.length == 0) return false; // already the active tab, ignore click
                
                // remove .current from selected tab
                $this.closest('div').find(classSelector).removeClass( opts.selectedClass );
                
                selectTab($this, opts.selectedClass);
                
                // hide content siblings - show the current tab's content
                content.siblings('.block_content:visible').hide().end().show();
                
                return false;
            });
            
            // select first tab?
            if (index == 0 && opts.selectFirstTab) { 
                selectTab($this, opts.selectedClass);
                content.show();
            }
        });
    };
    
    // helper function that marks given tab as selected
    function selectTab($tab, cssClass) {
        var selectElem;
        var parent = $tab.parent().parent();
        
        // where do we want to add the current class?
        if (parent.is('li')) selectElem = parent;
        else selectElem = $tab;
        
        selectElem.addClass( cssClass );
    }
})(jQuery);

/* options: {title: '', autoClose: bool} */
function alert(msg, options) {
    options = jQuery.extend({
        title: 'Informasjon',
        autoClose: false
    }, options);

	var alerter = jQuery('#alert');

	if (options.autoClose) alerter.data('autoClose', true);
	if (options.title.length > 0) alerter.find('div.jqmAlertTitle h1:first').html(options.title);
    alerter.find('div.jqmAlertContent').html(msg).end().jqmShow();
}    
    
/* Overriding Javascript's Confirm Dialog */
function confirmBox(msg,callback,title) {
    if (title == undefined) title = '';

    jQuery('#confirm')
    .jqmShow()
    .find('p.jqmConfirmMsg')
      .html(msg)
    .end()
    .find(':submit:visible')
      .click(function(){
        if(jQuery(this).is('.yes'))
          (typeof callback == 'string') ? window.location.href = callback : callback();
        
        jQuery('#confirm').jqmHide();
      })
    .end()
    .find('div.jqmConfirmTitle h1:first')
        .html(title);
}