(function($){ 
  $.fn.extend({  
    limit: function(limit,element) {
			
      var interval, f;
      var self = $(this);
					
      $(this).focus(function(){
	interval = window.setInterval(substring,100);
      });
			
      $(this).blur(function(){
	clearInterval(interval);
	substring();
      });
			
      substringFunction = "function substring(){ var val = $(self).val();var length = val.length;if(length > limit){$(self).val($(self).val().substring(0,limit));}";
      if(typeof element != 'undefined')
	substringFunction += "if($(element).html() != limit-length){$(element).html((limit-length<=0)?'0':limit-length);}"
      substringFunction += "}";
      eval(substringFunction);
      substring();
    } 
  }); 
})(jQuery);

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;
 }
}; 

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





$(document).ready(function(){

  $("ul.slideshow").cycle();


  // IFRAME FRAMEBORDER = 0
  var iframe = document.createElement("iframe");
    iframe.frameBorder = 0;
  document.body.appendChild(iframe);


  //KARUSELL LTK
  if($("#ltk_caruselContainer").length){
    $('.slide').cycle({ 
      delay:  6000, 
      speed:  1000
    });
  };
  
//TEXTSIZE
var getTextSize = function() {
var textsize = $.cookie('textsize');
$(".summary,.article,#navMain,#navSub ul li a")
 .removeClass("default")
 .removeClass("small")
 .removeClass("medium")
 .removeClass("large").addClass(textsize);
};
getTextSize();
$("#aboveheader span").not("#navTop").click(function(event){
  $target = $(event.target);
  if ($target.is("span")) {
    $.cookie('textsize', $target.attr("id"), { expires: 300, path: '/'});
  }
  getTextSize();
  return false;
});  

  // OBJECT COMMENTS



  var $comments = jQuery(".comments"); // CACHE
  if ($comments.length) {
	$comments.find(".ajax").each(function(){
	  $comments.load($(this).attr("href"), function(){
            var writeACommentText = jQuery("#writeACommentText") ? jQuery("#writeACommentText").text() : "Skriv en kommentar." ;
            var commentPostedText = jQuery("#commentPostedText") ? jQuery("#commentPostedText").text() : "Kommentaren er lagt til og venter moderering." ;
            var $commentForm = $("#commentForm"); //CACHE
            $("#comment").limit('100', '#charsLeft');
	    if($commentForm.length) {
	      $commentForm.submit(function(event){
	         var $this = $(this), //CACHE
	             $response = $("#objectResponse"),  //CACHE
	             $signature = $this.find("#signature"),  //CACHE
	             $comment = $this.find("#comment"); //CACHE
	         event.preventDefault();
	         if ($comment.val() === "") {
	           $response.text(writeACommentText);
	           $comment.addClass("error");
	         } else {
	           $.post(urlroot, $this.serialize(), function(){
               $("<li class='comment'><p>" + $signature.val() + "</p><p><strong>" + $comment.val() + "</strong></p></li>").appendTo("ul.commentList");
	             $response.text(commentPostedText);
               $(".noComments").hide();
               var postdata = {"action" : "FormMailer.submitPostcard",
                               "module" : "pubforms",_ips_encoding : "utf-8",
                               "ipsfm_msgtemplate" : $signature.val()+' skrev en kommentar. Produkt: "'+$(document).attr("title").replace(" : Kommuneforlaget","")+'".\n\n Kommentar:\n\n '+$comment.val()+'\n\n Hvis du er logget inn kan du godkjenne den her:\n\nhttp://'+window.location.hostname+urlroot+'admin/IPS?module=ObjectComments;action=ObjectComments.listAllComments',
                               "ipsfm_subject" :'Noen skrev en kommentar. Produkt: "'+$(document).attr("title").replace(" : Kommuneforlaget","")+'"',
                               "ipsfm_recipients":"grete.tjonneland@kommuneforlaget.no,lise.storholdt@kommuneforlaget.no",
                               //"ipsfm_recipients":"frederic@idium.no",
                               "ipsfm_fromfromemail":"robot@kommuneforlaget.no",
                               "ipsfm_fromname":"Kommentarer"};
                               
                               //
                                
               $.post(urlroot,postdata);
	             $comment.removeClass("error").val("");
	           });
	         }
	      });
	    } 
	  });
	});
  } // END COMMENTS																								


// ##### JS validation for custom webshop register form 

if($("#userForm").length && $("#billingInfo").length) { // reg form for orgs is on page
  $("#userForm").submit(function() {
    if($("#attribute31").val() == '' || $("#attribute33").val() == '' || $("#attribute34").val() == '' || $("#attribute43").val() == '') {
      alert("Alle felt med * m\u00E5 fylles ut");
      return false;
    }
    else return true;
  });
} 

if($("#userForm").length && $(".personType li:eq(1) a.selected").length) { // reg form for privates is on page
  $("#userForm").submit(function() {
    if($("#attribute31").val() == '' || $("#attribute37").val() == '' || $("#attribute38").val() == '' || $("#attribute39").val() == '') {
      alert("Alle felt med * m\u00E5 fylles ut");
      return false;
    }
    else return true;
  });
} 


  // ----------------- SEARCH RESULT SIDEMAL ---------------------
  var query = ips.data.params.query || "public:true";
  var lang = ips.data.params.lang;

 /* $(".updateresult").live("click", function (event) {
    event.preventDefault();
    $(this).closest("div.searchresult").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=EventCalendar.Event&qroot=1&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + "no" + "&template=searchResults&index=" + $(this).attr("rel"));
  });
*/

  if ($("#searchProducts").length) {
    $("#searchProducts").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=Webshop.Product&qroot=2&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + "no" + "&template=searchResults");
  }

  if ($("#searchArticles").length) {
    $("#searchArticles").load(urlroot + "?module=Search&action=Search.publicSearch&qtype=Articles.Article&qroot=39&pagesize=" + ips.system.pagesize + "&query=" + query + "&lang=" + "no" + "&template=searchResults");
  }



$("#sameAsDelivery").bind("click",function() {
                     moveValsBetweenInputs("attribute43","attribute69");
                     moveValsBetweenInputs("attribute37","attribute31");
                     moveValsBetweenInputs("attribute38","attribute33");
                     moveValsBetweenInputs("attribute39","attribute34");
                    });

jQuery(".ltk_login #username,.ltk_login input[type='password']").bind("focus",function(){
  jQuery(this).prev().hide();
}).bind("blur",function(){
  if(jQuery(this).val().length<1) {
    jQuery(this).prev().show();
  }
}).val('');

$("#auth").unbind().bind("submit",function(e) {
  e.preventDefault();
  var $this = $(this);
  var serviceBaseURL = 'http://www.tjenestekatalog.no/loginjsonp?';
  $.ajax({
    dataType: 'jsonp',
    jsonpCallback: 'callbackFunc',  
    url: serviceBaseURL + $(this).serialize() , 
    success: function (data) {
      $this.find(".response").remove();
      if(data.success == true) {
        window.location = data.url;
      }
      else if (data.orgselect !== undefined) { // system is asking for which organisation the user belongs to
        var $orgPicker = $("<select name='orgselect' />");
        for (var x=0;x < data.orgselect.length;x++) {
          $orgPicker.append("<option value='"+data.orgselect[x].value+"'>"+data.orgselect[x].label+"</option>")
        }
        var $orgPickerHTML = $("<li class='orgPicker response'><label for='orgselect'>" + data.message + ":</label></li>");
        $orgPickerHTML.append($orgPicker);
        $this.find("li.submit").before($orgPickerHTML);
        $this.append('<input type="hidden" name="' + data.token.name + '" value="' + data.token.value + '" />');
        $this.find("li.required").fadeOut();
      }
      else { // probably wrong password
        $this.find("li.required").fadeOut();
        $this.find("li.submit").before("<li class='error response'><strong>Feil brukernavn eller passord. <a href='#'>Pr&#248;v igjen</a>.</strong></li>");
        $this.find(".error a").unbind().bind("click",function() {
          $this.find(".response").remove();
          $this.find(".required").fadeIn(); 
        });
      }
    }
  });
});

}); // ######  END OF CODE RUN ON DOCUMENT READY #########

var moveValsBetweenInputs = function(from,to) {
  $("#"+to).val($("#"+from).val());
}


function facebook_click() {
  u=location.href;
  t=document.title;
  window.open('http://www.facebook.com/sharer.php?u='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=626,height=436');
  return false;
}

function linkedin_click() {
  u=location.href;
  t=document.title;
  window.open('http://www.linkedin.com/shareArticle?mini=true&url=' + encodeURIComponent(u) + '&title=' + encodeURIComponent(t),'sharer','toolbar=0,status=0,width=810,height=436');
  return false;
}

function twitter_click() {
  u=location.href;
  t=document.title;
  window.open('http://twitter.com/home?status='+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=810,height=436');
  return false;
}

function buzz_click() {
  u=location.href;
  t=document.title;
  window.open('http://www.addthis.com/bookmark.php?pub=&amp;v=250&amp;source=tbx-250&amp;tt=0&amp;s=buzz&amp;url=http%3A%2F%2Fwww.tipsotricks.com%2F2010%2F03%2Fadd-google-buzz-share-button-with.html&amp;title=Add%20Google%20Buzz%20Share%20Button%20with%20Counter%20in%20Your%20Blog%2FSite%20%7C%20TipsoTricks%20-%20Computing%20and%20Blogging%20Tips&amp;content=&amp;lng=nb'+encodeURIComponent(u)+'&t='+encodeURIComponent(t),'sharer','toolbar=0,status=0,width=810,height=436');
  return false;
}
