$j(function(){
  $j(".box-list").each(function(){ $j(this).etpEqualHeight("box-content-wrapper", 148, 148); });
  $j(".effect-button").each( function(){ $j(this).etpButtonHover("effect-button-hover"); });
  $j("h2.hover").each(function(){ $j(this).etpBackgoundPositionChange("0" , "100"); }); 
  $j(".home-page .box-content").each(function(){ $j(this).etpContentPositionChange("100", "1000"); });
  $j(".picture-overlay").etpAjaxStatusBind();
  $j(".picture-menu a").each(function(){ $j(this).etpMoveContent("picture-overlay"); });
  $j(".slide-frame").each(function(){ $j(this).etpSlideShow(); });
  
  $j(".form-person-trigger").each(function(){
    $j(this)
    .click(function(){ 
      $parent = $j(this).parent().parent();
      if($parent.etpValidateAllInputsLength(1,500))
      {
        if($parent.attr("id").indexOf("school") > 0)
        {
          $j(this).addSkischoolRow($j(".skischool-order"));
        }
        else
        { 
          $j(this).addSkiRentalRow($j(".ski-rental-order"));
        }
      }
    })
    .mouseover(function(){ $j(this).css({cursor: "pointer"}) });
  });
  
  $j("#formSkirental").submit(function(){ return($j(this).etpValidateAllInputsLength(1,500)); });
  $j("#formSkischool").submit(function(){ return($j(this).etpValidateAllInputsLength(1,500)); });
    
  $j(".datepicker").datepicker($j.datepicker.regional["no"]);
 
	$j("#accordion").accordion({collapsible: true, active: false, autoHeight: false });
	$j(".accordion").accordion({collapsible: true, active: false, autoHeight: false });
	$j("#tabs").tabs();
	   
});

   

// Functions
(function($){

  $.fn.etpValidateAllInputsLength = function(min, max){
  
      var cValid = true;      
      var resultPane = $(".result-pane", $(this));
      
      if(min && max)
      {
        $("input",$(this)).each(function()
        {                     
          //Epostfelt
          if($(this).attr("name").indexOf("epost") > -1){ cValid = cValid && checkEmail($(this),$(this).attr("name"), resultPane);}          
          
          // Alle inputfelt
          cValid = cValid && checkLength($(this),$(this).attr("name"),min,max, resultPane);
        });
        
        $("select",$(this)).each(function(){ cValid = cValid && checkLength($(this),$(this).attr("name"),min,max, resultPane);});
      } 
  
      return (cValid);        
  };

  $.fn.etpEqualHeight = function(elementClass, minHeight, maxHeight)
  { 
    var outerHeighest = 0;
    if(minHeight < 1){ minHeight = 1; }
    
    $("." + elementClass, $(this)).each(function(){
      if($(this).innerHeight(true) > outerHeighest){ outerHeighest = $(this).innerHeight(true); }

    });
    
    if(outerHeighest < minHeight){outerHeighest = minHeight; }
    if(outerHeighest > maxHeight){outerHeighest = maxHeight; }
    
    $("." + elementClass, $(this)).each(function(){
      $(this).height(outerHeighest);
    });
  }    

  
  var closeOverlay = false;
  var showOverlay = true;
  
  $.fn.etpMoveContent = function(container)
  {        
    var $cur = $(this);
    var curTimeout = null;
    var $c = $("." + container);
    $(".picture-overlay-close", $c)
      .click(function(){ $(this).parent().css({display: "none"});})
      .mouseover(function(){ $(this).css({cursor: "pointer"}); });        
       
    $cur
    //.click(function(){ return false; })
    .mouseover(function(){
        $(".picture-menu a").removeClass("active");
        $cur.addClass("active");
        closeOverlay = false;
        clearTimeout(curTimeout);                
        if(showOverlay) {
          showOverlay = false;
          setTimeout(function(){ if(!showOverlay){$c.stop().show(); showOverlay = true; } }, 1100);
        }        
        $info = $($(this).next());
        $("div.pad", $c).html($info.html());
    })      
    .mouseout(function(){ 
      closeOverlay = true;   
      curTimeout = setTimeout(function(){ if(closeOverlay){ $c.hide(); showOverlay = true; $cur.removeClass("active"); } }, 500);       
    });
    
    $c.mouseover(function()
    { 
        clearTimeout(curTimeout); 
        closeOverlay = false;
    })
    .mouseout(function(){ 
      closeOverlay = true;
      curTimeout = setTimeout(function(){ if(closeOverlay){ $c.hide(); showOverlay = true; $cur.removeClass("active"); } }, 500);       
    });
            
  }

 $.fn.etpContentPositionChange = function(posX)
  {
    var posX = (posX) ? posX : 0;
    var $trigger = $(this);
    var $el = $trigger.parent().next();
    var $el2 = $("div", $el);
    
    var $h = $el2.show().height() + 10;
    $el2.hide();

    $trigger
    .mouseover(function(){
      $l = $el2.html().length; 
      if($l > 16) { $el2.stop().show().css({ marginTop: "-" + $h + "px"}); }
    })
    .mouseout(function() { $el2.stop().hide().css({ marginTop: 0 + "px"}); });
    
    $el2
    .mouseover(function(){
      $l = $el2.html().length; 
      if($l > 16) { $el2.stop().show().css({ marginTop: "-" + $h + "px"}); }
    })
    .mouseout(function(){ $el2.stop().hide().css({ marginTop: 0 + "px"}); });

  }
  
  /* $.fn.etpContentPositionChange = function(posX, delay)
  {
    var posX = (posX) ? posX : 0;
    var $el = $("div.hover" ,$(this));
    var $trigger = $("h2.hover", $(this));
    $trigger = $el.parent();
    
    $trigger
    .mouseover(function()
    { 
      $el.stop().animate({ paddingLeft: "5%", paddingRight: posX + "%"});

    })
    .mouseout(function() 
    { 
      $el.stop().animate({paddingLeft: posX  + "%", paddingRight: "5%"}) 
    });     
  } */
            

  $.fn.etpBackgoundPositionChange = function(posX, posY)
  {
    var posX = (posX) ? posX : 0;
    var posY = (posY) ? posY : 0; 
        
    $(this)
    .mouseover(function(){ $(this).css({backgroundPosition: posX + '% ' + posY  + '%'});})
    .mouseout(function(){ $(this).css({backgroundPosition: '0 0'}); });     
    
  }            

  $.fn.etpButtonHover = function(className)
  {            
      if(className){ classToToggle = className;}    
      
      $(this)
      .mouseover( function(){ $(this).etpToogleClass(classToToggle);  })
      .mouseout(  function(){ $(this).etpToogleClass(classToToggle);  });                    
  }
  
  $.fn.etpToogleClass = function(className)
  {            
      var classToToggle = "";
      if(className){ classToToggle = className;}   
      $(this).toggleClass(classToToggle);      
  }  


  // IE6 - dropdown
  $.fn.etpIE6DropDownMenu = function()
  {
    $(this).children("li").each(function()
    {
      $(this)
      .mouseover(function(){ $(this).stop().addClass("sfhover"); })
      .mouseout(function(){ $(this).stop().removeClass("sfhover"); });
    });        
  }


  $.fn.etpClock = function(language)
  {
    var lang = "no";
    if (language){ lang = language; } 
    
    return "Ikke implementert!";
  }
  
  // Returnerer et navn ut fra når på dagen. Bruker klient-tid
  $.fn.etpGetPartOfDay = function(klasser, tidspunkt)
  {
    var curKlasser = ["morgen", "dag", "kveld"];
    var curTidspunkt = [720, 1080];
    var retKlasse = "";      
            
    if(klasser)   { curKlasser = klasser; }
    if(tidspunkt) { curTidspunkt = tidspunkt; }
                    
    var dag = new Date(),
        time = dag.getHours(),
        minutt = dag.getMinutes(),
        sekund = dag.getSeconds();
        
    var totalMin = (time * 60) + minutt;
    
    for(var i = 0; i < curTidspunkt.length; i++)
    {
      if(totalMin < curTidspunkt[i])
      { 
        retKlasse = curKlasser[i];
        continue; 
      }
      else
      {
        retKlasse = curKlasser[curKlasser.length - 1];
      }
    }              
    this.addClass(retKlasse).show();
  }
    
  
  $.fn.etpAjaxStatusBind = function(){ 
    $("this").bind("ajaxStart", setStatusText($(this),"Starting..."));  
    $("this").bind("ajaxSend", setStatusText($(this),"Sending..."));  
    $("this").bind("ajaxSuccess", setStatusText($(this),"Success!"));  
    $("this").bind("ajaxComplete", setStatusText($(this),"Completed!"));  
  }
 
  function err(xhr, reason, ex){ $("body").prepend("Err:" + reason + "<br />"); }
  function setStatusText(el, text){ $().prepend(text + "<br />"); }

  var skiSchoolCounter = 1;
  $.fn.addSkischoolRow = function(tbl){  
    
    //$(".form-ski-rental-submit-info").hide();
    $(".form-skischool-btn-submit").show();
    $tbl = $("tbody", tbl);

    var $navn = $("#navn" + skiSchoolCounter);
    var $alder = $("#alder" + skiSchoolCounter);
    var $epost = $("#epost" + skiSchoolCounter);
    var $telefon = $("#telefon" + skiSchoolCounter);
    var $dato = $("#dato" + skiSchoolCounter);
    var $tid = $("#tid" + skiSchoolCounter);
    var $type = $("#type" + skiSchoolCounter);
    var $klasse = $("#klasse" + skiSchoolCounter);
    var $ferdighet = $("#ferdighet" + skiSchoolCounter);

    // Neste
    $("#dato" + (skiSchoolCounter+1)).val($dato.val());
    $("#telefon" + (skiSchoolCounter+1)).val($telefon.val());
    $("#epost" + (skiSchoolCounter+1)).val($epost.val());
    
    
    if ($navn.val() != "") 
    { 
      $j(this).parent().parent().removeClass("current-area").addClass("area").hide();
      $j(this).parent().parent().next().removeClass(".area").addClass("current-area").show();

      $("#tr-default").remove(); 
      
      $tbl.prepend("<tr>" +
  							     "<td>" + skiSchoolCounter + "</td>" +
  							     "<td>" + $navn.val() + "</td>" +
  							     "<td> Klasse: " + $klasse.val() + ". Ferdighet: " + $ferdighet.val() +"</td>" +
                     "<td>" + 
                      "<input type='hidden' name='" + $navn.attr("id") + "' value='" + $navn.val() + "' />" + 
                      "<input type='hidden' name='" + $alder.attr("id") + "' value='" + $alder.val() + "' />" + 
  							      "<input type='hidden' name='" + $dato.attr("id") + "' value='" + $dato.val() + "' /></td>" + 
  							      "<input type='hidden' name='" + $tid.attr("id") + "' value='" + $tid.val() + "' /></td>" + 
                      "<input type='hidden' name='" + $type.attr("id") + "' value='" + $type.val() + "' /></td>" + 
                      "<input type='hidden' name='" + $klasse.attr("id") + "' value='" + $klasse.val() + "' /></td>" +
                      "<input type='hidden' name='" + $ferdighet.attr("id") + "' value='" + $ferdighet.val() + "' /></td>" +   							                              							      
                      "<input type='hidden' name='" + $epost.attr("id") + "' value='" + $epost.val() + "' /></td>" +   							                              							      
                      "<input type='hidden' name='" + $telefon.attr("id") + "' value='" + $telefon.val() + "' /></td>" +   							                              							      
  							   "</tr>").show();                   
      skiSchoolCounter = skiSchoolCounter + 1; 

    }
    else{
      alert("Du må skrive inne et navn!");
    }
  }

  var skiRentalCounter = 1;
  $.fn.addSkiRentalRow = function(tbl){
        
    $(".form-ski-rental-submit-info").hide();
    $(".form-ski-rental-btn-submit").show();
    $tbl = $("tbody", tbl);

    var $navn = $("#navn" + skiRentalCounter);
    var $alder = $("#alder" + skiRentalCounter);
    var $fra = $("#fra" + skiRentalCounter);
    var $til = $("#til" + skiRentalCounter);
    var $hoyde = $("#hoyde" + skiRentalCounter);
    var $type = $("#type" + skiRentalCounter);
    var $sko = $("#sko" + skiRentalCounter);
    var $vekt = $("#vekt" + skiRentalCounter);
    var $ferdighet = $("#ferdighet" + skiRentalCounter);
    var $kommentar = $("#kommentar" + skiRentalCounter);

    // Neste
    $("#fra" + (skiRentalCounter+1)).val($fra.val());
    $("#til" + (skiRentalCounter+1)).val($til.val());
    
    
    if ($navn.val() != "") 
    { 
      $j(this).parent().parent().removeClass("current-area").addClass("area").hide();
      $j(this).parent().parent().next().removeClass(".area").addClass("current-area").show();

      $("#tr-default").remove(); 
      
      $tbl.prepend("<tr>" +
  							     "<td>" + skiRentalCounter + "</td>" +
  							     "<td>" + $navn.val() + "</td>" +
  							     "<td> Type: " + $type.val() + ". Ferdighet: " + $ferdighet.val() +"</td>" +
                     "<td>" + 
                      "<input type='hidden' name='" + $navn.attr("id") + "' value='" + $navn.val() + "' />" + 
                      "<input type='hidden' name='" + $alder.attr("id") + "' value='" + $alder.val() + "' />" + 
  							      "<input type='hidden' name='" + $fra.attr("id") + "' value='" + $fra.val() + "' /></td>" + 
                      "<input type='hidden' name='" + $til.attr("id") + "' value='" + $til.val() + "' />" + 
                      "<input type='hidden' name='" + $hoyde.attr("id") + "' value='" + $hoyde.val() + "' />" + 
                      "<input type='hidden' name='" + $type.attr("id") + "' value='" + $type.val() + "' /></td>" + 
                      "<input type='hidden' name='" + $sko.attr("id") + "' value='" + $sko.val() + "' /></td>" + 
                      "<input type='hidden' name='" + $vekt.attr("id") + "' value='" + $vekt.val() + "' /></td>" +
                      "<input type='hidden' name='" + $ferdighet.attr("id") + "' value='" + $ferdighet.val() + "' /></td>" +   							                              							      
                      //"<input type='hidden' name='" + $kommentar.attr("id") + "' value='" + $kommentar.val() + "' /></td>" +
                      "<textarea style='display: none;' name='" + $kommentar.attr("id") + "'>" + $kommentar.val() + "</textarea></td>" + 
  							   "</tr>").show();                   
      skiRentalCounter = skiRentalCounter + 1; 

    }
    else{
      alert("Du må skrive inne et navn!");
    }
  }
  

  $.fn.etpSlideShow = function()
  {     
    function play(){ scroll("n"); }

    var timer = null;
    var delay = 6000;

    $ss = $(this);
    
    setTimeout(function(){play();}, delay);

    
    $(".btn-prev", $ss).click(function(){ clearTimeout(timer); scroll("p"); });
    $(".btn-next", $ss).click(function(){ clearTimeout(timer); scroll("n"); });
               
    function scroll(dir)
    {          
      var $active = $('.slide-image.active', $ss);
      if ( $active.length == 0 ) $active = $('img.slide-image:last', $ss);
  
      // use this to pull the images in the order they appear in the markup
      var $next =  $active.next().length ? $active.next() : $('.slide-image:first', $ss);
      var $prev =  $active.prev().length ? $active.prev() : $('.slide-image:last', $ss);
      
      $active.addClass('last-active');
      
      if(dir == "p")
      { 
        $prev.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() 
            { 
              $active.removeClass('active last-active');
            });
      }
      else
      { 
        $next.css({opacity: 0.0})
            .addClass('active')
            .animate({opacity: 1.0}, 1000, function() 
            { 
              $active.removeClass('active last-active');
            });
      }
      
      timer =  setTimeout(function(){play();}, delay);
    }

        
  }
})(jQuery);

/* General jquery functions */

function checkCheckbox(o,n,checked,resObj)
{
  var c = (o.attr("checked") || o.is(":checked"));
  if(c)
  {
    return true;
  }
  else
  {
    o.addClass('ui-state-error'); 
    updateTips(n, resObj);
    return false;
  }  
}

function checkLength(o,n,min,max, resObj) 
{ 

  if ( o.val().length > max || o.val().length < min ) { 
    o.addClass('ui-state-error'); 
    updateTips("Felt: " + n + ".  Ugyldig lengde (min: "+min+", max: "+max+")", resObj); 
    return false;
  } 
  else { return true; }
}

function checkEmail(o,n,resObj)
{
  bValid = true;
  //bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
  bValid = bValid && checkRegexp(o,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,n,resObj);
  //"(.*)@(.*)"
  return (bValid);
}

function checkRegexp(o,regexp,n,resObj) {
if (!(regexp.test(o.val()))) {
  o.addClass('ui-state-error');
  updateTips("Ugyldig epostformat", resObj);
  return false;
  }
  else { return true;}
}

function updateTips(t, obj){ obj.text(t).effect("highlight",{},1500); }

function goToUrl(url){ 
  if(url){
    if(url.indexOf("http://") > 0) { window.open(url); }
    else{ document.location = url; } 
  } 
}
