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

var errors = [];

//master.js
jQuery(document).ready(function($) {
var isIE = navigator.userAgent.indexOf("MSIE") == '-1' ? false : true;

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


// AUTO COMPLETE
  $(".query").autocomplete().focus(function(e){
    if (!ips.data.words) {
      $.getJSON(ips.system.base + "?template=words", function(data){
      ips.data.words = data.words;
      $(".query").autocomplete(data.words);
      });
    }
});

$('#login_form').bind('submit', function(){
  setTimeout(
    function() {
      window.location.href = ips.system.base;
    },
    1000
  )
});

$("#newsticker").newsticker();

//LOGIN
$('.ajax_login').load(base + '?template=ajaxLogin&ajax=true&redirect=' + encodeURIComponent(window.location.toString()));

$(window).load(function(){
  	var $gmaps = $("a[href*=http://maps.google] img");
	if ($gmaps.size()) {
	  // miniplugin
	  jQuery.fn.makeObj = function() {
		    href = this.eq(0).attr("href");
		    var splitted = href.substring( href.indexOf("?")+1 ).split("&"), obj = {}; 
		    // iteratte and make a workable obj
		    for ( var i = 0; i < splitted.length; i++ ) {
		      var ins = splitted[i].split("=");
		      if (ins[1] !== undefined && ins[1] !== "") obj[ ins[0] ] = ins[1];
		    }
		    return obj;		 
	  };
	  //Iterate imgs
	  $gmaps.each(function(i){
	    var $t = $(this), $p = $t.parent(), 
	        obj = $p.makeObj(),
	        width  = $t.width()*1 > 10 ? $t.width() : 200,
	        height = $t.height()*1 > 10 ? $t.height() : 300,
	        elem   = "<div class='gmap' style='position:relative;width:"+width+"px; height:"+height+"px'>";
	        elem  += "<div class='gmap"+i+"' style='width:100%;height:100%;'></div>";
	        elem  += "<a class='gmaplink"+i+"' target='_blank' style='display:none;position:absolute;";
	        elem  += "top:2px;right:2px;z-index:1000' href='"+$p.attr("href")+"'>Se fullt kart</a></div>";
	        var view = obj.ll ? obj.ll.split(",") : obj.sll.split(","),
	        setupObj = {
	          "zoom" : obj.z *1,
	          "center": new google.maps.LatLng( view[0]*1, view[1]*1 ),
	          "mapTypeId" : google.maps.MapTypeId.ROADMAP,
	          "disableDefaultUI" : true
	        };
	    $p.replaceWith(elem);
	    var gmapref = new google.maps.Map($(".gmap"+i).get()[0], setupObj),
	        point = obj.ll ? obj.ll.split(",") : obj.sll.split(","),
	        marker = new google.maps.Marker({
		        position: new google.maps.LatLng( point[0]*1, point[1]*1 ), 
		        map: gmapref,
		        title: obj.q||obj.hnear||''
		    });
	    $(".gmap").hover(function(){$(this).find(".gmaplink"+i).toggle();});
	  });
	}
});




   // Searchform interaction
   var $searchForm = $("#searchForm"), //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");
  });


   // IPSFORM navn
   var $ipsform = $(".ipsform"), //CACHE
       $input1 = $ipsform.find("#articles_articlecontent_147_e49"),
       $label1 = $ipsform.find("#labelarticles_articlecontent_147_e49");
   if ($input1.val() !== "") {$label1.hide();}
   $ipsform.submit(function(){
   if ($input1.val() === "") {return false;}
   });
   $input1.focus(function(){$label1.hide();}).blur(function(){
     if ($(this).val() === "") {$label1.show();}
   });
   $ipsform.find("#labelarticles_articlecontent_147_e49").click(function(){
    $input.focus();
   }); 


   // IPSFORM epost
   var $ipsform = $(".ipsform"), //CACHE
       $input2 = $ipsform.find("#articles_articlecontent_147_e50"),
       $label2 = $ipsform.find("#labelarticles_articlecontent_147_e50");
   if ($input2.val() !== "") {$label2.hide();}
   $ipsform.submit(function(){
   if ($input2.val() === "") {return false;}
   });
   $input2.focus(function(){$label2.hide();}).blur(function(){
     if ($(this).val() === "") {$label2.show();}
   });
   $ipsform.find("#labelarticles_articlecontent_147_e50").click(function(){
    $input.focus();
   }); 


   // IPSFORM melding
   var $ipsform = $(".ipsform"), //CACHE
       $input3 = $ipsform.find("#articles_articlecontent_147_e51"),
       $label3 = $ipsform.find("#labelarticles_articlecontent_147_e51");
   if ($input3.val() !== "") {$label3.hide();}
   $ipsform.submit(function(){
   if ($input3.val() === "") {return false;}
   });
   $input3.focus(function(){$label3.hide();}).blur(function(){
     if ($(this).val() === "") {$label3.show();}
   });
   $ipsform.find("#labelarticles_articlecontent_147_e51").click(function(){
    $input.focus();
   }); 

   // IPSFORM hva soker du etter
   var $ipsform = $(".ipsform"), //CACHE
       $input4 = $ipsform.find("#articles_articlecontent_155_e52"),
       $label4 = $ipsform.find("#labelarticles_articlecontent_155_e52");
   if ($input4.val() !== "") {$label4.hide();}
   $ipsform.submit(function(){
   if ($input4.val() === "") {return false;}
   });
   $input4.focus(function(){$label4.hide();}).blur(function(){
     if ($(this).val() === "") {$label4.show();}
   });
   $ipsform.find("#labelarticles_articlecontent_155_e52").click(function(){
    $input.focus();
   }); 

   // IPSFORM antall treff
   var $ipsform = $(".ipsform"), //CACHE
       $input5 = $ipsform.find("#articles_articlecontent_155_e53"),
       $label5 = $ipsform.find("#labelarticles_articlecontent_155_e53");
   if ($input5.val() !== "") {$label5.hide();}
   $ipsform.submit(function(){
   if ($input5.val() === "") {return false;}
   });
   $input5.focus(function(){$label5.hide();}).blur(function(){
     if ($(this).val() === "") {$label5.show();}
   });
   $ipsform.find("#labelarticles_articlecontent_155_e53").click(function(){
    $input.focus();
   }); 


  // 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 if .required and 
      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;
    // default action of the event will not be triggered.
    //e.preventDefault();
    // Keeps the rest of the handlers from being executed.
      //e.stopImmediatePropagation();
    }
  });
  // Possible to click the errors away
  $("span.error").live("click", function(){$(this).fadeOut();}); 
//FORM END


if(ips.system.parameters.folderpagesize == 100) {
  var elementCount = $(".summary").length;
  var pagecount = Math.ceil(elementCount/6); //  number up to the nearest upper integer
  $('#content').evtpaginate({perPage:6});
  var paginationHtml = "<ul class='pagination'></ul>";
  $("#content").append(paginationHtml);
  for(x=1;x<(pagecount+1);x++) {
    $(".pagination").append("<li><a href='#"+x.toString()+"'>"+x.toString()+"</a></li>");
  }
  $("#content").append("<ul class='prevNext'><li class='prevPage'><a href='#' class='prevPage'>Forrige</a></li><li class='nextPage'><a href='#' class='nextPage'>Neste</a></li></ul>");
 var paginationWidth = $("ul.pagination").width();
$("ul.prevNext").width(paginationWidth);

$(".nextPage").click(function(e) {
  e.preventDefault();
  $("#content").trigger('next.evtpaginate');
});

$(".prevPage").click(function(e) {
  e.preventDefault();
  $("#content").trigger('prev.evtpaginate');
});


$(".pagination li a:first").addClass("current");

$(".pagination li a").live("click",function(e) {
  e.preventDefault();
  $('html, body').animate({scrollTop:0}, 25);
  $(".pagination li a").removeClass("current");
  var index = $(this).parent().index();
  var oneindex = isIE ? index : (index+1);
  $.historyLoad(this.href.replace(/^.*#/, ''));
  $(".pagination").each(function() {
    $(this).find("a[href='#"+oneindex+"']").addClass("current");
  });
  $('#content').trigger('show.evtpaginate', oneindex );
});
}

function callback(hash)
{
    // do stuff that loads page content based on hash variable
}

$.historyInit(callback);
/*$("a[@rel='history']").click(function(){
  $.historyLoad(this.href.replace(/^.*#/, ''));
  return false;

});
*/
function callback(hash)
{
  if(hash) {
    $('#content').trigger('show.evtpaginate', hash );
    $(".pagination li a").removeClass("current");
    $(".pagination").each(function() {
      $(this).find("li:eq("+(hash-1)+") a").addClass("current");
    });
    $('html, body').animate({scrollTop:0}, 'slow');
  }
  else {
    $('#content').trigger('show.evtpaginate', 1);
    $(".pagination li a").removeClass("current");
    $(".pagination").each(function() {
      $(this).find("li:eq("+(1-1)+") a").addClass("current");
    });
    $('html, body').animate({scrollTop:0}, 'slow');
  }
}

jQuery.fn.equals = function(selector) {
	return $(this).get(0)==$(selector).get(0);
};

jQuery.fn.validation = function() {
  var $this = $(this), formid = $(this).equals('form') ? $this.attr("id")+"" : $(this).closest('form').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 if .required and 
    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;
  // default action of the event will not be triggered.
  //e.preventDefault();
  // Keeps the rest of the handlers from being executed.
    //e.stopImmediatePropagation();
  } else {
    return true
  }
}

/*
$('.rel a[href$="id=397"], .rel a[href$="id=396"]').click(function(e) {
  if($('#applyForm').length == 0) {
    $('body').prepend($('<div>').attr('id', 'applyForm').corner('10px').css({'left': $('#main').offset().left + 100, 'top': $('#main').offset().top + 50,position:'absolute'}).load($(this).attr('href') + ';template=stepbystep'));
  }
  e.preventDefault();
});
*/

$('.close').live('click', function(e) {
  $('#applyForm').remove();
  e.preventDefault();
});

$('a.step').live('click', function(e) {
  var url = e.target.href.replace(/^(.*)#/, ''),
      $this = $(this);
  var $step = $this.closest('li.step'),
      $nextStep = $('#' + url);

  if($this.hasClass('next') && !$step.validation()) {
    e.preventDefault()
  } else if(($step.validation() && $this.hasClass('next')) || $this.hasClass('prev')) {
    $('li.step').each(function() {
      $(this).hide(0, function() {
        $nextStep.show(0);
      })
    })
  }
})

$('#applyForm form').live('submit', function(e) {
  e.preventDefault();
  e.returnValue = false;
  e.stopImmediatePropagation();
  var $this = $(this);
  $.post(ips.system.base + "?" + $this.serialize(), function(data) { $('#applyForm').html(data) })
});

}); // EOF DOCUMENT READY
