/*!
 * jQuery Cycle Lite Plugin
 * http://malsup.com/jquery/cycle/lite/
 * Copyright (c) 2008 M. Alsup
 * Version: 1.0 (06/08/2008)
 * Dual licensed under the MIT and GPL licenses:
 * http://www.opensource.org/licenses/mit-license.php
 * http://www.gnu.org/licenses/gpl.html
 * Requires: jQuery v1.2.3 or later
 */
(function(D){var A="Lite-1.0";D.fn.cycle=function(E){return this.each(function(){E=E||{};if(this.cycleTimeout){clearTimeout(this.cycleTimeout)}this.cycleTimeout=0;this.cyclePause=0;var I=D(this);var J=E.slideExpr?D(E.slideExpr,this):I.children();var G=J.get();if(G.length<2){if(window.console&&window.console.log){window.console.log("terminating; too few slides: "+G.length)}return }var H=D.extend({},D.fn.cycle.defaults,E||{},D.metadata?I.metadata():D.meta?I.data():{});H.before=H.before?[H.before]:[];H.after=H.after?[H.after]:[];H.after.unshift(function(){H.busy=0});var F=this.className;H.width=parseInt((F.match(/w:(\d+)/)||[])[1])||H.width;H.height=parseInt((F.match(/h:(\d+)/)||[])[1])||H.height;H.timeout=parseInt((F.match(/t:(\d+)/)||[])[1])||H.timeout;if(I.css("position")=="static"){I.css("position","relative")}if(H.width){I.width(H.width)}if(H.height&&H.height!="auto"){I.height(H.height)}var K=0;J.css({position:"absolute",top:0,left:0}).hide().each(function(M){D(this).css("z-index",G.length-M)});D(G[K]).css("opacity",1).show();if(D.browser.msie){G[K].style.removeAttribute("filter")}if(H.fit&&H.width){J.width(H.width)}if(H.fit&&H.height&&H.height!="auto"){J.height(H.height)}if(H.pause){I.hover(function(){this.cyclePause=1},function(){this.cyclePause=0})}D.fn.cycle.transitions.fade(I,J,H);J.each(function(){var M=D(this);this.cycleH=(H.fit&&H.height)?H.height:M.height();this.cycleW=(H.fit&&H.width)?H.width:M.width()});J.not(":eq("+K+")").css({opacity:0});if(H.cssFirst){D(J[K]).css(H.cssFirst)}if(H.timeout){if(H.speed.constructor==String){H.speed={slow:600,fast:200}[H.speed]||400}if(!H.sync){H.speed=H.speed/2}while((H.timeout-H.speed)<250){H.timeout+=H.speed}}H.speedIn=H.speed;H.speedOut=H.speed;H.slideCount=G.length;H.currSlide=K;H.nextSlide=1;var L=J[K];if(H.before.length){H.before[0].apply(L,[L,L,H,true])}if(H.after.length>1){H.after[1].apply(L,[L,L,H,true])}if(H.click&&!H.next){H.next=H.click}if(H.next){D(H.next).bind("click",function(){return C(G,H,H.rev?-1:1)})}if(H.prev){D(H.prev).bind("click",function(){return C(G,H,H.rev?1:-1)})}if(H.timeout){this.cycleTimeout=setTimeout(function(){B(G,H,0,!H.rev)},H.timeout+(H.delay||0))}})};function B(J,E,I,K){if(E.busy){return }var H=J[0].parentNode,M=J[E.currSlide],L=J[E.nextSlide];if(H.cycleTimeout===0&&!I){return }if(I||!H.cyclePause){if(E.before.length){D.each(E.before,function(N,O){O.apply(L,[M,L,E,K])})}var F=function(){if(D.browser.msie){this.style.removeAttribute("filter")}D.each(E.after,function(N,O){O.apply(L,[M,L,E,K])})};if(E.nextSlide!=E.currSlide){E.busy=1;D.fn.cycle.custom(M,L,E,F)}var G=(E.nextSlide+1)==J.length;E.nextSlide=G?0:E.nextSlide+1;E.currSlide=G?J.length-1:E.nextSlide-1}if(E.timeout){H.cycleTimeout=setTimeout(function(){B(J,E,0,!E.rev)},E.timeout)}}function C(E,F,I){var H=E[0].parentNode,G=H.cycleTimeout;if(G){clearTimeout(G);H.cycleTimeout=0}F.nextSlide=F.currSlide+I;if(F.nextSlide<0){F.nextSlide=E.length-1}else{if(F.nextSlide>=E.length){F.nextSlide=0}}B(E,F,1,I>=0);return false}D.fn.cycle.custom=function(K,H,I,E){var J=D(K),G=D(H);G.css({opacity:0});var F=function(){G.animate({opacity:1},I.speedIn,I.easeIn,E)};J.animate({opacity:0},I.speedOut,I.easeOut,function(){J.css({display:"none"});if(!I.sync){F()}});if(I.sync){F()}};D.fn.cycle.transitions={fade:function(F,G,E){G.not(":eq(0)").css("opacity",0);E.before.push(function(){D(this).show()})}};D.fn.cycle.ver=function(){return A};D.fn.cycle.defaults={timeout:4000,speed:1000,next:null,prev:null,before:null,after:null,height:"auto",sync:1,fit:0,pause:0,delay:0,slideExpr:null}})(jQuery);

// MASTER JS
// SWFobject for IPS by sveinung@idium.no Feb 2010
(function f(b){var d=window.ips=window.ips||{},c=b||{loading:false},e;if(d.queue===undefined)d.queue=[];if(typeof window.swfobject!=="undefined"&&typeof window.swfobject.embedSWF!=="undefined")c.loading=false;else if(d.queue.length>0){if(c.loading===false){b=document.createElement("script");b.type="text/javascript";b.async=true;b.src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(b); c.loading=true}e=setTimeout(function(){f(c)},50)}if(c.loading===false&&d.queue.length>0)for(b=0;b<d.queue.length;b++){var a=d.queue[b];if(!a.loaded){a.loaded="true";swfobject.embedSWF(a.url,a.element,a.width,a.height,a.version,a.expressInstall,a.flashvars,a.params,a.attributes)}}if(c.loading===false&&typeof window.jQuery!=="undefined")e=setTimeout(function(){jQuery(document).one("ajaxStart",function(){e=setTimeout(function(){f(c)},100)})},2E3)})();


//master.js
jQuery(document).ready(function($) {


  // GOOGLE MAP
  if ($("#google_maps").length) {
    var map;
    var markers = [];
    initializeMap();
  }
  function initializeMap() {
    var latlng = new google.maps.LatLng(ips.container["locationsContainer"].longitude, ips.container["locationsContainer"].langitude);
    var options = {
      zoom: parseInt(ips.container["locationsContainer"].zoom),
      center: latlng,
      mapTypeControl: false,
      mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    map = new google.maps.Map(document.getElementById('google_maps'), options);
    initMarkers();


  }
  function initMarkers() {
    var backupicon = 'dev/GFX/map/aktuelt_icon.png';
    $.each(ips.locations.children, function(i, object) {
      var marker = new google.maps.Marker({
        position: new google.maps.LatLng(object.longitude, object.langitude),
        title: object.name,
        icon: ips.system.base + 'filestore/' + (object.icon ||backupicon),
        map: map
      });
      var infowindow = new google.maps.InfoWindow({
        content: '<strong>'+marker.title + '</strong><br /><br />' + 
        (object.content !== undefined ? object.content+'<br />' : '')  +
        (object.visitaddress !== undefined ? object.visitaddress+'<br />' : '') +
        (object.contenttelephone !== undefined ? object.contenttelephone+'<br />' : '')  +
        (object.contentfax !== undefined ? object.contentfax+'<br /><br />' : '') +
        (object.title !== undefined ? object.title+' : ' : '') +
        (object.email !== undefined ? '<a href="mailto:' +object.email + '">' : '') +
        (object.representative !== undefined ? object.representative: '') +
        (object.email !== undefined ? '</a><br /><br />' : '') +
        (object.contentdescription !== undefined ? object.contentdescription+'<br /><br />' : '') +
        '<a  class="mer_info" href="' +
        (object.contentlink !== undefined ? object.contentlink : '') +
        '" >' +
        (object.contentlink !== undefined ? 
          '<img src="'+ips.system.base+'filestore/dev/GFX/greenArrow.png" /> Mer info' 
         : ''
        ) +
        '</a>'
      });

      google.maps.event.addListener(marker, 'click', function() {
        infowindow.open(map, marker);
      });

/*    console.log(marker.position);
      console.log(marker.title);
      console.log(marker.icon);
      console.log(marker.map);*/
      markers.push(marker);
    });
  }  

   // UTILITY
   var base = ips.system.base; //cache as local variable

   // Searchform interaction
   var $searchForm = $("#search_form"), //CACHE
       $query = $searchForm.find(".query"),
       $label = $searchForm.find("label");
   if ($query.val() !== "") {$label.hide();}
   $searchForm.submit(function(){
   if ($query.val() === "") {return false;}
   });
   $query.focus(function(){$label.hide();}).blur(function(){
     if ($(this).val() === "") {$label.show();}
   });
   $searchForm.find("label").click(function(){
    $query.focus();
   }); 


  // EVENT DELEGATION - Not touching dom until click
  $(".externalLink").live("click", function(){
    $(this).attr("target", "_blank");
  });


  // IPS FORM validation by sveinung@idium.no March 2010
  $("body").delegate("form", "submit", function(e){
    var $this = $(this), formid = $this.attr("id")+"", errors = [];
    // Start validation object
    //fix broken objects
    var ips = window.ips = window.ips ||{};
    ips.validate = ips.validate ||{};
    ips.validate[formid] = ips.validate[formid] ||{};
    //end fix broken objects

  // Reset, and FIND/QUERY viable <li> tags. Must be typical <li> with input. If different, change next find().
    $this.find("span.error").remove().end().find("li:not(.submit,.form_labelfield)").removeClass("error")
    // START each - > iterate li`s
    .each(function(i){
    // Needed vars and Cache selectors for convenience and "speed"
      var $li = $(this), $nextLi = $li.next(), $prevLi = $li.prev(), $field = $li.find("input,textarea,select").eq(0), fid = $field.attr("id"), fieldval = $field.val(), errorObj = {"id":fid,"$elem":$li,"message":""};
      // Utilty function for checking regex values
      var checkFunc = function(regexObj, thisval, message, errorObj){
      if (!regexObj.test(thisval)) {
        errorObj.message = message;
      } else {
        errorObj.valid = true; // used to make this rule more important than classes
      }
      return errorObj;  
      };
      // Iterating and validation all regexes in the general object
      $.each(ips.validate.general, function(property){
      if ($li.hasClass(property) && this.regex !== undefined ) {
        errorObj = checkFunc(this.regex, fieldval, this.message, errorObj);
      }
      });
      // Check for validation object
    if ( ips.validate[formid][fid] !== undefined && ips.validate[formid][fid].regex !== undefined ) {
     var fieldvalObj = ips.validate[formid][fid],
           errorMgs = fieldvalObj.message !== undefined ?  fieldvalObj.message : ips.strings.notvalid;
       errorObj = checkFunc(new RegExp(fieldvalObj.regex), fieldval, errorMgs, errorObj);
      } else {
      //fix missing objects
      ips.validate[formid][fid] = {};
      }
      if ( $li.hasClass("form_password") && errorObj.message === ''){
        errorObj = checkFunc(ips.validate.general.password.regex, fieldval, ips.validate.general.password.message, errorObj);
        if (errorObj.message === "" && fieldval !== $li.find(".confirm").val()) {
        errorObj.id = $li.find(".confirm").attr("id");
        errorObj.message = ips.validate.general.password.message;
        }
      }
      // Check username if form has class .loggedout -> Forms get resubmitted if error from server
      if ( $this.hasClass("loggedout") && $li.hasClass("username") && !(errorObj.valid)){
        var searchedUsername = $.data($field[0],"username"), // get "cacge"
            availFromPrevSubmit = $.data($field[0],"avail"); // get "cache"
        $.data($field[0],"username",fieldval); // write "cache"
        // Check if new desired username isnt equal to previous ones or if no username has been checked
        if ((fieldval !== searchedUsername) || (availFromPrevSubmit === null) ) { 
        // Async - check param, then set value on elem and resubmit form
        $.get(ips.system.base + "?module=Users&amp;action=Ajax.isUsernameAvailable&amp;username="+fieldval, function(data){
         $.data($field[0],"avail",data);
         // 'false' is serverresponse in plain text
         if (data == 'false') {
           setTimeout(function(){$this.submit();},100);
         }
        });
        } else {
        // check if this is checked and username is not avail === false
        if (availFromPrevSubmit == "false") {
          errorObj.message = ips.strings.usernamenotavail;  
        }  
        }
      }
      	// Check custom class, and recheck _class
      var testCustom = /required_if_not_([a-zA-Z0-9]+)/.exec($li.attr("class"));
      if (testCustom && testCustom[1] && testCustom[1] !== '') {
          if ($("." + testCustom[1]).find("input,textarea,select").eq(0).val() == '') {
              // if other field has no value, this field is required
              $li.addClass("required");
          } else {
              // if other field has value, this field isnt required
              $li.removeClass("required");
          }
          // check if .required and 
      } else if (fieldval === '' &&  $li.hasClass("required")) {
        // If not already a error - add a error message
      if (errorObj.message === '') {
          errorObj.message = ips.strings.cannotbeempty;
     }
      } else if ($li.hasClass("required") && errorObj.message === '') {
        // if checkbox is required
        if ($field.is("input[type=checkbox]") && $field.attr("checked") === false) {
          errorObj.message = ips.validate[formid][fid].message ||ips.strings.mustbechecked;
        }
      }
      // Todo, ADD : requiredIf - (e.g. email, checkbox )
      // Check for customclasses 'isequaltonext' and 'isequaltoprev' - > is in lowercase bacause of ips:classify
    if ($li.hasClass('isequaltonext')||$nextLi.hasClass('isequaltoprev')) {
        if (fieldval !== $nextLi.find("input").val()) {
        errorObj.message = $li.find("label").text() + ips.strings.mustbeequalto + $nextLi.find("label").text();
        }
      }  else if ($li.hasClass('isequaltoprev')||$prevLi.hasClass('isequaltonext')) {
        if (fieldval !== $prevLi.find("input").val()) {
        errorObj.message = $li.find("label").text() +  ips.strings.mustbeequalto + $prevLi.find("label").text();
        }
      }
      // Field is not required, NO error-msg should be generated
      if (fieldval === '' && !($li.hasClass("required"))) {
      errorObj.message = ''; 
      }
      // Push this errorObj if there is a message defined
      if ( errorObj.message !== undefined && errorObj.message !== '' ) {
      errors.push(errorObj);
      }
    }); //END each li`s

    if ( ips.system.parameters.debug ) {
      console.log(errors);
    }  // Process errors if there is any
    if ( errors.length > 0 ) {
      $( errors ).each(function(i){
        var $errorField = this.$elem.addClass("error").find("input,textarea,select").eq(0);
        if (i === 0) {$errorField.focus();}
        $("<span class='error'>" + this.message + "</span>").insertAfter( $errorField );  
      });
      return false;
    }
  });
  // Possible to click the errors away
  $("span.error").live("click", function(){$(this).fadeOut();}); 
//FORM END
});

// TOGGLE
$(".toggle").not("a").hide();
$("a.toggle").click(function(){
$(this).next(".toggle").toggle("slow");
return false;
}); //END TOGGLE 




if($(".bottomCarusel").length){

    $('.carusel').cycle({ 
      delay:  2000, 
      speed:  1000
    });
  };


//------------------
   // VALIDATE E-MAIL.
   // - ToDo: Remove this
   //------------------
   var emailpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;

   //----------------------------
   // Newsletter form interaction
   // - Hides label when click on input 
   //----------------------------
   var $newsletter = $(".newsletter_form"), //CACHE
       $emailNewsletter = $newsletter.find(".email"),
       $labelNewsletter = $newsletter.find("label");
   if ($emailNewsletter.val() !== "") {$labelNewsletter.hide();}
   $newsletter.submit(function(){
   if ($emailNewsletter.val() === "") {return false;}
   });
   $emailNewsletter.focus(function(){$labelNewsletter.hide();}).blur(function(){
     if ($(this).val() === "") {$labelNewsletter.show();}
   });
   $newsletter.find("label").click(function(){
    $emailNewsletter.focus();
   });

//--------------------
  // NEWSLETTER SIGN UP
  //--------------------
  jQuery(".newsletter_form").submit(function(e){
    e.preventDefault();
    var $this = jQuery(this); //cache
    var $email = $this.find("input.email"); //cache
    var $fieldsetNewsletter = $this.find("fieldset");
    if(!$this.find(".response").get()[0]) {
      jQuery("<p class='response' />").appendTo($this);
    }
    var $response = $this.find(".response"); // Cache
    if (emailpattern.test($email.val())) {
      $response.text("....");
      $.ajax({
        url: "?template=newsletterResponse",
        data: $this.serialize(),
        error: function() {
          $response.text("Feil / Error");
        },
        success: function(data) {
          if(ips.system.lang == 'no' ) {
             $response.text("Din epost adresse er lagt til");
          }
          else if (ips.system.lang == 'se') { 
             $response.text("Tack for din registrering");
          }
          else { 
             $response.text("Tak for din registrering");
          }
          $email.removeClass("error").val("");
          $fieldsetNewsletter.addClass("hide");
        }
      });
    } else {
      $email.addClass("error");
       if(ips.system.lang == 'no' ) {
             $response.text("Skriv inn din e-postadresse");
          }
          else if (ips.system.lang == 'se') { 
             $response.text("Skriv in din e-postadress");
          }
          else { 
             $response.text("Indtast din e-mail-adresse");
          }
          $email.removeClass("error").val("");
          $fieldsetNewsletter.addClass("hide");
        }
  });
