$(document).ready(function(){
    var $search = $('.sHolder').addClass('overlabel');
    var $searchInput = $search.find('input');
    var $searchLabel = $search.find('label');
    
    if($searchInput.val()){
	$searchLabel.hide();
    }
    
    $searchInput
    .focus(function(){
	$searchLabel.hide();
    })
    .blur(function(){
	if (this.value == ''){
	    $searchLabel.show();
	}
    })
    
    $searchLabel.click(function(){
	$searchInput.trigger('focus');
    })
    
    
})

var gridUrl;

$(document).ready(function() {
            
    // Creates tab-function for the core content module
    $("#core-content").tabs();
    
    // Turn off the grid
    gridUrl = $("#grid").css("background-image");
    $("#grid").css("background", "none");
    
    // Assorted functions controlled by the keyboard
    /*$(document).keypress(function (e) {
      switch(e.which) {
      case 115:   // 's'
        $(".comment").fadeOut("slow");
        break;
      case 118:  // 'v'
        $(".comment").fadeIn("slow");
        break;
      case 103:  // 'g'
        // toggle grid-background TODO: make grid as an overlay -> see blueprint canvas grid
        if ( $("#grid").css("background-image") == "none") {
          $("#grid").css("background", gridUrl);
        }
        else {
          gridUrl = $("#grid").css("background-image");
          $("#grid").css("background", "none");
        }
        break;
      }
    });
     */
        
    // Toggle the local menus
    $("#site-menu > li > a").click(function () {
      
      var isVisible = $("#site-menu").find(".submenu").is(':visible');
      var selectedElement = $(this).parent();
	  //var highest = 0;
      
      if (isVisible) {
        // De-highlight selected submenu
        $("#site-menu > li").removeClass("selected");
      }
      /* else {
       $(this).parent().addClass("selected");
      } */
    
      // Toggle submenus
      $("#site-menu").find(".submenu").animate({height: "toggle"}, 250, 'linear', function () {
          if (isVisible) {
            // De-highlight selected submenu
            $("#site-menu > li").removeClass("selected");
          }
          else {
            selectedElement.addClass("selected");
		    // update submenu heights if current submenu is the heighets so far
			//if (this.clientHeight > highest)
			//{
			//	highest = this.clientHeight;
			//}
    	    //$("#site-menu .submenu").height(highest);
          }
        } );
  
      return false;        // return false to avoid bubling and default action.
    });
    
    // Highlight submenu item on hover
    /*$(".submenu > li > a").hover( 
      function() {
       $(this).parent().addClass("hover"); 
      },
      
      function() {
       $(this).parent().removeClass("hover"); 
      }
    ); */
    
    // Toggle the fagtilbud-menu
    $("#title-fagomraade").click(function () {
      elem = $("#fagomraader");		
      elem.slideToggle("fast");
      return false;        // return false to avoid bubling and default action.
    });
    
    // Toggle the feedback form
    
    $("a.feedback").click(function () {
      $("#tip-a-friend").slideUp("fast");
      $("#feedback").slideToggle("fast");
      return false;
    });
        
    
    // Toogle the tip-a-friend form
    
    /*
    $("a.tip-a-friend").click(function () {
      $("#feedback").slideUp("fast");
      $("#tip-a-friend").slideToggle("fast");
      return false;
    });
    */
    
    
    // Toggle the UB search forms
    $(".ub-search h4").click(function () {
	$(".ub-search .ub-input").slideUp("fast");
        $(this).next(":hidden").slideDown("fast");
	$(".ub-input input[type=text]", this).focus();
	return false;
    });
    
    $(".ub-input").hide();
    $(".ub-search:first .ub-input").show()
    
    
    // Print document
    $("a.print, .print").click(function () {
      window.print()
      return false;
    });
    
    $(".tip-a-friend").click(function(){
        
    });
    
	 
	 //not-implemented
   $(".not-implemented").submit(function () {
    alert("Denne funksjonen er ikke implementert i demoversjonen.");
    return false;
   });
   
   $("a.not-implemented").click(function () {
    alert("Denne funksjonen er ikke implementert i demoversjonen.");
    return false;
   });
   
   // Runde hjørner
   //$(".rounded, #infocard, .navigation .summary-list, .testimonial, .studieretning, #create, #login-page form, #personal-update, #topic-search #filters").corner();
   
    // Toogle the video
    $("a.selectvideo").click(function () {
	  var videoclass = $(this).parent().attr('class');
	  var elem = $("#" + videoclass);
	  elem.slideToggle("fast");	  
	  //$("#videoview").slideToggle("fast");	 
      return false;
    });	 
    $("a.close").click(function () {  
      var elem = $("#videoview > div");
      //$("#videoview").slideUp("fast");
      elem.slideUp("fast");  	
      return false;
    });     

    $("img.video_click").click(function(event) {        
        tb_show($(event.target).attr("tittel"), $(event.target).parents("a.thickbox").attr("link"), null, {height: 500, width: 430});
        event.stopPropagation();
        event.preventDefault();
        return false;		
    });
    $("img.video_click_uselinksize").click(function(event) {        
        tb_show($(event.target).parents("a.thickbox").attr("title"), $(event.target).parents("a.thickbox").attr("link"), null);
        event.stopPropagation();
        event.preventDefault();
        return false;		
    });
    

    if (navigator.userAgent.match(/iPhone/)) {
	$("a.sms").show();
    }
});



/****************

Fra previewtools.js 

***********/

var viewInfoOn = false;

$(document).ready(function() {
            
    // Assorted functions controlled by the keyboard
    $(document).keypress(function (e) {
      if (e.originalEvent.altKey) {         // We are only interessted in keypresses in combination with the Alt-key.
        switch(e.which) {
        
        case 115:   // 's'
          $(".comment").fadeOut("slow");
          break;
        
        case 118:  // 'v'
          // toggle view information (information about how the current page is put together with pagelets, viewlet managers and viewlets)
          if ( viewInfoOn ) {
            // Hide view info
            $(".view-info").css("display", "none");
            viewInfoOn = false;
            return false;
          }
          else {
            // Show view info
            $(".view-info").css("display", "block");
            viewInfoOn = true;
            return false;
          }
          break;
        
        case 103:  // 'g'
          // toggle grid - graphical overlay that represent the design grid for the templates
          if ( $("#grid").length ) {
            $("#grid").remove();    // The grid is switched on - remove it
          }
          else {                    // The grid is switched off - add it
            $("body#uib-no").prepend('<div id="grid"></div>');
          }
          return false;
          break;
        }  // switch(e.which)
      }  // if(e.altKey)
            
    });  // $(document).keypress
    
    $(".viewletname").click(function (e) {
      if ( $(this).hasClass("selected") ) {
        $(this).removeClass("selected")
      }
      else {      
        $(".viewletname").removeClass("selected");
        $(this).addClass("selected");
      }
    });  // $(".viewletname").click

    $(".viewletname").hover(function (e) {
      
      if ($(".viewletname").hasClass("selected")) {
        $(".viewletname").removeClass("selected");
        $(this).addClass("selected");
      }
      else {
        $(".viewletname").removeClass("selected");
      }
    },
    function(e){}
    );  // $(".viewletname").hover

});



/**
* Styleswitch stylesheet switcher built on jQuery
* Under an Attribution, Share Alike License
* By Kelvin Luck ( http://www.kelvinluck.com/ )
**/

$(document).ready(function() {
	$('.styleswitch').click(function()
	{
		switchStylestyle(this.getAttribute("rel"));
		return false;
	});
	var c = readCookie('style');
	if (c) switchStylestyle(c);
});

function switchStylestyle(styleName)
{
	$('link[@rel*=style][@title]').each(function(i) 
	{
		this.disabled = true;
		if (this.getAttribute('title') == styleName) this.disabled = false;
	});
	createCookie('style', styleName, 365);
}

// cookie functions http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days)
{
	if (days)
	{
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name)
{
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++)
	{
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name)
{
	createCookie(name,"",-1);
}
// /cookie functions



/*
cbb function by Roger Johansson, http://www.456bereastreet.com/
*/
var cbb = {
	init : function() {
	// Check that the browser supports the DOM methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oOuter, oI1, oI2, tempId;
	// Find all elements with a class name of cbb
		var arrElements = document.getElementsByTagName('*');
		var oRegExp = new RegExp("(^|\\s)cbb(\\s|$)");
		for (var i=0; i<arrElements.length; i++) {
	// Save the original outer element for later
			oElement = arrElements[i];
			if (oRegExp.test(oElement.className)) {
	// 	Create a new element and give it the original element's class name(s) while replacing 'cbb' with 'cb'
				oOuter = document.createElement('div');
				oOuter.className = oElement.className.replace(oRegExp, '$1cb$2');
	// Give the new div the original element's id if it has one
				if (oElement.getAttribute("id")) {
					tempId = oElement.id;
					oElement.removeAttribute('id');
					oOuter.setAttribute('id', '');
					oOuter.id = tempId;
				}
	// Change the original element's class name and replace it with the new div
				oElement.className = 'i3';
				oElement.parentNode.replaceChild(oOuter, oElement);
	// Create two new div elements and insert them into the outermost div
				oI1 = document.createElement('div');
				oI1.className = 'i1';
				oOuter.appendChild(oI1);
				oI2 = document.createElement('div');
				oI2.className = 'i2';
				oI1.appendChild(oI2);
	// Insert the original element
				oI2.appendChild(oElement);
	// Insert the top and bottom divs
				cbb.insertTop(oOuter);
				cbb.insertBottom(oOuter);
			}
		}
	},
	insertTop : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the top of the box
		oOuter=document.createElement("div");
		oOuter.className="bt"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.insertBefore(oOuter,obj.firstChild);
	},
	insertBottom : function(obj) {
		var oOuter, oInner;
	// Create the two div elements needed for the bottom of the box
		oOuter=document.createElement("div");
		oOuter.className="bb"; // The outer div needs a class name
	    oInner=document.createElement("div");
	    oOuter.appendChild(oInner);
		obj.appendChild(oOuter);
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener(type, fn, false);
		else if (obj.attachEvent) {
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent("on"+type, obj[type+fn]);
		}
	}
};

function externalLinks() {
 if (!document.getElementsByTagName) return;
 var anchors = document.getElementsByTagName("a");
 for (var i=0; i<anchors.length; i++) {
   var anchor = anchors[i];
   if (anchor.getAttribute("href") &&
	   anchor.getAttribute("rel") == "external")
	 anchor.target = "_blank";
 }
}
window.onload = function() {
externalLinks();
}

cbb.addEvent(window, 'load', cbb.init);



$(document).ready(function() {
    var selectItem = function (li) {
			if (li.extra) {
				self.location = li.extra[0]

			}
		}
    var formatItem = function (row) {
        return row[0] ;//+ "<br><i>" + row[1] + "</i>";
    }


	var searchField = $("#searchField, #searchField2");
    if( searchField.autocomplete ) {
        var searchForm = searchField.parents("form")
        var formAction = searchForm.attr("action");
        var autocompleteSearchURL = formAction.replace("/search","/@@uibsearchautocomplete");
        searchField.autocomplete(autocompleteSearchURL,
                                   { minChars:3, 
                                     matchSubset:0, 
                                     matchContains:1, 
                                     //cacheLength:10, 
                                     onItemSelect:selectItem, 
                                     formatItem:formatItem, 
                                     selectOnly:1 });
    }
});



