// 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)})();

jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
        options = options || {};
        if (value === null) {
            value = '';
            options = $.extend({}, options); // clone object since it's unexpected behavior if the expired property were changed
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        // NOTE Needed to parenthesize options.path and options.domain
        // in the following expressions, otherwise they evaluate to undefined
        // in the packed version for some reason...
        var path = options.path ? '; path=' + (options.path) : '';
        var domain = options.domain ? '; domain=' + (options.domain) : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};


function switchStylestyle(styleName) {
  $('link[@rel*=style][title]').each(function(i) {
    this.disabled = true;
    if (this.getAttribute('title') == styleName) {this.disabled = false;$(".contrast > .contrast").hide();$(".contrast > .default").show();} else {$(".contrast > .contrast").show();$(".contrast > .default").hide();}
  });
  $.cookie('style', styleName, { expires: 365, path: '/'});
  
}





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

var urlroot2 = window.location.host.indexOf('idium.n') !== -1 ? window.location.pathname.substring(0,window.location.pathname.indexOf('/',2)) + "/" : "/";

$("#Map area").qtip({
   content: $(this).attr("alt"),
   style:{background:'url('+urlroot2+'filestore/tooltipbg.png) repeat-x',color:'white'/*border:'1px solid #fff'*/},
   position: {
      corner: {
         target: 'center',
         tooltip: 'bottomLeft'
      },
   hide :{ fixed:true }
   }
});

  //TEXTSIZE
   var getTextSize = function() {
     var textsize = $.cookie('textsize');
     $(".wrapper")
.removeClass("default")
.removeClass("small")
.removeClass("medium")
.removeClass("large").addClass(textsize);
   };
   getTextSize();
   $("#sizeSelector").click(function(event){
       $target = $(event.target);
       if ($target.is("span")) {
         $.cookie('textsize', $target.attr("class"), { expires: 300, path: '/'});
       }
       getTextSize();
       return false;
   });

  //$('.fp_box').append($('<div class="faux_border"></div>'));


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

  // ARTICLE CARUSEL
  var $carusel = $('ul.article-carusel');
  if ($carusel.size()) {
    $carusel.after('<li class="nav_carusel clearfix"></li>').cycle({ 
        speed:  'slow', 
        timeout: 3000, 
        pager:  '.nav_carusel',
        next:   '#next2', 
        prev:   '#prev2',
        pause:   1
    });

  }

   // Searchform interaction
   var $searchForm = $("#search_form"), //CACHE
       $query = $searchForm.find(".query"),
       $label = $searchForm.find("#search_form_lquery");
   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("#search_form_lquery").click(function(){
    $query.focus();
   }); 

   // Log in
   var $loginForm = $("#login_form"), //CACHE
       $user = $loginForm.find("#username"),
       $label1 = $loginForm.find(".user");
   if ($user.val() !== "") {$label1.hide();}
   $loginForm.submit(function(){
   if ($user.val() === "") {return false;}
   });
   $user.focus(function(){$label1.hide();}).blur(function(){
     if ($(this).val() === "") {$label1.show();}
   });
   $loginForm.find(".user").click(function(){
    $user.focus();
   }); 


   // Log in
   var $loginForma = $("#login_form"), //CACHE
       $pass = $loginForma.find("#password"),
       $label2 = $loginForma.find(".pass");
   if ($pass.val() !== "") {$label2.hide();}
   $loginForma.submit(function(){
   if ($pass.val() === "") {return false;}
   });
   $pass.focus(function(){$label2.hide();}).blur(function(){
     if ($(this).val() === "") {$label2.show();}
   });
   $loginForma.find(".pass").click(function(){
    $pass.focus();
   }); 
   

  // IPS FORM validation by sveinung@idium.no March 2010
  $("body").live("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
});
