//cookie
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
        }
        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;
    }
};
//jquery center
jQuery.fn.center = function (absolute) {
	return this.each(function () {
		var t = jQuery(this);

		t.css({
			position:	absolute ? 'absolute' : 'fixed', 
			left:		'50%', 
			top:		'50%'
		}).css({
			marginLeft:	'-' + (t.outerWidth() / 2) + 'px', 
			marginTop:	'-' + (t.outerHeight() / 2) + 'px'
		});

		if (absolute) {
			t.css({
				marginTop:	parseInt(t.css('marginTop'), 10) + jQuery(window).scrollTop(), 
				marginLeft:	parseInt(t.css('marginLeft'), 10) + jQuery(window).scrollLeft()
			});
		}
	});
};


//master.js
jQuery(document).ready(function($){
   var emailpattern = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
   var $body = $("body");
   ips.system.state = {"loading":false};
   var $loader = $("<div class='loader'></div>").appendTo("#wrapper").center();
   var loading = ips.system.state.loading;
   function startLoading(text){
     //console.log("start loading");
     $body.addClass("loading");
     $loader.text(text);
     loading = true;
   }
   function stopLoading(text){
     //console.log("stop loading");
     $loader.text(text);
     setTimeout(function(){$body.removeClass("loading");$loader.text("");},500);
     loading = false;
   }
   var urlroot = ips.system.urlroot;
   var setupOverlay = function($this, callback){
      var obj = {};
      obj.w = $(window).width();
      obj.h = $(document).height() > $(window).height() ? $(document).height() : $(window).height();
      obj.wb = 1000; //Math.floor(1* obj.w * 0.8);
      obj.hb = 600; //Math.floor(1* obj.h * 0.8);
      obj.oldsrc = $this.attr("src");
      obj.src = obj.oldsrc.substr(0,obj.oldsrc.indexOf("?")) + "?size=" + obj.wb + "x" + obj.hb;
      obj.title = $this.attr("alt") !== "" ? $this.attr("alt") : $this.attr("title") !== "" ? $this.attr("title") : "";
      obj.content = "<div id='overlay' style='height:" + obj.h + "px;'></div><div id='overlaybox'><div id='overlaycontainer'><img id='overlayimg' src='" + obj.src + "' /><h3>" + obj.title + "</h3></div></div>";
      var preload = [obj.src];
      for (var i = 0;i<preload.length;i++) {
        preload[i] = new Image();
	    $(preload[i]).attr("src",obj.src).load(function(){
		  if ($("#overlaybox").length === 0) {
	        $body.prepend(obj.content);
	      } else {
	        $("#overlay,#overlaybox").filter(":hidden").show();
	        $("#overlayimg").attr("src", obj.src);
	        $("#overlaycontainer h3").text(obj.title);
          }
          $("#overlay").css("opacity","0.6");
          $("#overlaycontainer").hide();
          if (typeof callback === "function") {callback(obj);} 
		});
	  }

  };
  var $images = $("#mainColumn img,.headerWrapper img").live("click", function(e){
    if (!$(this).parents().is("a")) {
      setupOverlay($(this).clone(), function(obj){
	      $("#overlayimg").load(function(){
		    setTimeout(function(){
		      $("#overlaycontainer").center().fadeIn();
			},100);
		  });
      });
    }
  });
  $("#overlay,#overlaybox,#overlayimg").live("click", function(){
    $("#overlay,#overlaybox").hide();
  });
  // Slideshow
  if ($(".frontpageSlideshow").length) {
    $('.items').cycle({ 
      fx:     'fade', 
      speed:  1000, 
      timeout: 5000, 
      activePagerClass: 'active',
      pager:  '.navi' 
    });
  } 
  var objSearch = function(source, attr, val){ // util function
    var l = source.length;
    for(var i=0;i<l;i++) {
      if (source[i][attr] == val) {return i;}
    }
  };
  var delArray = function(source, index) { // util function
     source.splice(index,1);
  };
  var prodCounter = function(){
    var val = $(".prodcount").text();
    if (val > 0) {
		 $(".prodcount").text(1 * val -1);
	}
  };
  var drawCart = function(){
    $(".added").removeClass("added");
    var l = ips.data.cart.length;
    if (l) {
      var cart = ips.data.cart;
      var selectors = "";
      for(var i =0;i<l;i++){
        if (cart[i] !== undefined) {
			selectors += "#product" + cart[i].id + ",";
		}
      }
      //remove last ","
      selectors = selectors.substr(0,selectors.lastIndexOf(","));
      $(selectors).addClass("added");
      stopLoading();
    }
  };
  var removeProduct = function (id) {
	 startLoading("Fjerner..");
     $.get(urlroot + "?deleteItem" + id + "=on;quantity_" + id + "=0;module=Webshop;action=ShoppingBasketView.updateBasketQuantities;template=action",function(){
        delArray(ips.data.cart,objSearch(ips.data.cart,'id',id));
        prodCounter();
        $(".product" + id).hide("slow").remove();
        drawCart();
     });
  };
  var removeFavorite = function(id){
    var fid;
	if(isNaN(id)) {
		fid = 1*id.substring(3,10);
		startLoading("Fjerner oppskrift");
		$.get(urlroot + "?module=Favourites;action=Favourite.publicSetFavourite;object_id="+fid+";object_type=article;template=action", function(){
			$("#" + id).parent().parent().remove();
			stopLoading("Oppskrift fjernet");
		});
	} else {
		fid = id;
		startLoading("Fjerner oppskrift");
		$.get(urlroot + "?module=Favourites;action=Favourite.publicSetFavourite;object_id="+fid+";object_type=article;template=action", function(){
			stopLoading("Oppskrift fjernet");
		});
	}
	if (fid==ips.data.params.id) {
		$body.removeClass("infavorites");
	}
  };
  var dataReady = function(callback){
	$(".infavorites").removeClass("infavorites");
    var $favlist = $(".favlist");
    var container = "<li>Mine favorittoppskrifter</li>";
    if ($favlist.length && ips.data.favorites.length) {
      if (ips.data.user.user_name !== "") {
        var favlength = ips.data.favorites.length;
        var currid = ips.data.params.id;
        for(var i = 0;i<favlength;i++){
	  var o = ips.data.favorites[i];
          container += "<li><a href='"+urlroot+o.url+"'>"+o.title;
          container +="<span id='fav"+o.id+"'class='removefav' title='Fjern'>x</span></a></li>";
          if (o.id == currid) {
            $body.addClass("infavorites");
          }
        }
      }
      $favlist.html(container);
    }
    var $savedCarts = $(".savedCarts");
    if ($savedCarts.length) {
      if (ips.data.user.user_name === "") {
        if (typeof callback === "function") {callback();} 
      } else { 
		$.ajax({
		  url: urlroot + "scripts/customWebshopHandler.groovy?action=loadProductLists",
		  dataType: 'json',
		  cache: false,
		  success: function(data){
			var l = data.length, list = "<li><strong>Mine handlelister</strong></li>",uniq = "";
	         for (var i = 0; i < l; i++) {
	           var idstr = data[i][0] + ",";
	           if (uniq.indexOf(idstr) !== -1) {
	           } else if (ips.data.user.extra*1 == data[i][0]){ 
	             uniq += data[i][0] + ",";
	             list += "<li class='noaction' title='" + data[i][1] + "'><a href='" + urlroot + "?id=";
	             list += data[i][0]+"'>" + data[i][1];
	             list += "<span class='noaction'>[Gjeldende]</span></a></li>";
	           } else {
	             uniq += data[i][0] + ",";
	             list += "<li title='" + data[i][1] + "'><a href='" + urlroot + "?id=";
	             list += data[i][0]+"'>" + data[i][1];
	             list += "<span class='change' title='"+data[i][1]+"'>[Endre navn]</span></a></li>";
	           }
	         }
	         $savedCarts.append(list);
	         if (typeof callback === "function") {callback();}	
		  }
		});
      }
    } else {
      if (typeof callback === "function") {callback();} 
    }   
  };
  var updateUser = function(callback){
$.ajax({ 
type: "GET", 
url: urlroot + "?template=userjson", 
success: function(){
  if (ips.data.user.user_name !== '') {
     $body.addClass("loggedin");
  }
  dataReady(function(){drawCart();});
 }, 
dataType: "script", 
cache: false
}); 

/*    $.getScript(urlroot + "?template=userjson", function(){
       if (ips.data.user.user_name !== '') {
         $body.addClass("loggedin");
       }
       dataReady(function(){drawCart();});
    });*/
    $.get(urlroot + "?template=user", function(data){
      if ($("ul.user").length) {
        $("ul.user").replaceWith(data);
      } else {
        $(data).prependTo("div.support");
      }
      if (typeof callback === "function") {callback();} 
    });
  };
  updateUser(); // init

  $("a.add").click(function(e){ // add webshop product
    if (loading) {
      return false;
    }
    startLoading("Legger til...");
    e.preventDefault();
    var timer = ips.data.cart.length > 0 ? 500 : 1500;
    //console.log(timer);
    var $this = $(this);
    var prodid = $this.parent().attr("id").substring(7,12);
    if ($this.parent().hasClass("added")) {
        removeProduct(prodid);
        return false;
    }
    $this.parent().addClass("added");
    $.get($(this).attr("href") + "?template=action", function(data){
      var izhidden = $(".shoppingcart").is(":hidden");
      setTimeout(function(){
          updateUser(function(){ //callback action after cart is loaded
	        if (izhidden) {
	          $(".shoppingcart").slideDown("slow");
	        } else {
	          $(".shoppingcart").show();
	        }
	        if (window.location.toString().indexOf("shoppingcart") == -1) {
	          window.location = window.location + "#shoppingcart";
	        }
	        $(".product" + prodid).hide().addClass("latest").show("slow");
	      });  
      },timer);

    });
  });
  $(".favlist a").live("click",function(e){
	var $target = $(e.target);
    if ($(this).parent().is(".noaction") || $target.is(".noaction")) {
       return false;
    }
	if ($target.is("span")){
		e.preventDefault();	
		removeFavorite($target.attr("id")); 
	}	
  });
  $("a.remove").live("click", function(e){
    e.preventDefault();
    var id = $(this).attr("rel");
    removeProduct(id);    
  });
 $("a.pop").live("click", function(e){
   e.preventDefault();
   var $this = $(this);
   var w = 500;
   var h = 700;
   window.open($this.attr("href"),$this.attr("title"),'toolbar=0,status=0,width=' + w + ',height=' + h);
 });
 // general new window
 $(".closer").live("click", function(e){
    e.preventDefault();
    $(this).parent().hide();
 });
 $(".cartlink").live("click", function(e){
   if($(".shoppingcart").is(":hidden")) {
     $(".shoppingcart").slideDown();
     e.preventDefault();
   } 
 });
  //favorize 
  $(".favorize").live("click", function(e){
    e.preventDefault();
    startLoading("Lagrer oppskrift...");
    //
    if (ips.data.user.user_name === "") {
      window.location = urlroot + "?template=login;requestUrl=" + encodeURIComponent(window.location.toString());
      return false;
    }
    $.get($(this).attr("href") + ";template=action",function(){
      updateUser(function(){dataReady();});
    });
  });
  
  var customWebshopHandler = function(obj) {
    if (ips.data.user.user_name === "") {
      window.location = urlroot + "?template=login;requestUrl=" + encodeURIComponent(window.location.toString());
      return false;
    }
    if (loading) {return false;}
    startLoading("Laster...");
    if (obj.action == "loadBasket") {
      if (ips.data.user.extra === undefined) {
        var usererror = confirm("Er du sikker p\u00E5 at du vil slette listen du har \u00E5pen?");
        if (!usererror) {
          stopLoading("Handlingen ble stoppet.");
	      return false;
	    }
      }
    }
    var orderObj = {
      "action": obj.action,
      "redirectUrl":encodeURIComponent(urlroot+"?template=action;oldaction=" + obj.action),
      "paymentMethod":"invoice",
      "template":"action"
    };
    if (obj.name !== undefined) {
      orderObj.name = obj.name;
    }
    if (obj.id !== undefined) {
      orderObj.id = obj.id;
    }
    if (obj.email !== undefined) {
      orderObj.email = obj.email;
    }
    if (obj.id == ips.data.user.extra) {
      orderObj.updateCurrentUser = true;
    }
    var timer = 500;
    if (obj.action == "clearBasket") {
	  timer = 3500;
    }
    var orderUrl = urlroot + "scripts/customWebshopHandler.groovy?" + $.param(orderObj);
    $.ajax({
	  url : orderUrl,
	  cache : false,
          error : function(data){
            alert("Error: " + orderUrl + " ----- " + data);
          },
	  success : function(){
        setTimeout(function(){
          stopLoading("Lastet ferdig");
          window.location = urlroot + "?template=handleliste;oldaction=" + orderObj.action;
        },timer);
      }
    });
		
  };
  $(".save").live("click", function(e){ // save 
    e.preventDefault();
    customWebshopHandler({"action":"saveBasket"});

  });
  $(".new").live("click", function(e){ // clear
    e.preventDefault();
    customWebshopHandler({"action":"clearBasket"});
  });
  $(".send").bind("click", function(e){ // clear
    e.preventDefault();
    if (ips.data.user.user_name === "") {
      window.location = urlroot + "?template=login;requestUrl=" + encodeURIComponent(window.location.toString());
      return false;
    }
    var listBox = "<form id='emailform' class='listBox'><h3>Send handleliste</h3>";
    listBox += "<label>E-post<input type='text' id='useremail' value='";
    listBox += ips.data.user.email+"'></input></label><div class='button'><input class='submit'";
    listBox += " type='submit' value='Send'></input></div></form>";
    $(listBox).appendTo($(this).parent());
    $("#emailform").one("submit",function(e){
	  e.preventDefault();
	  customWebshopHandler({"action":"send", "email":$("#useremail").val()});
    });  
  });
  $(".change").live("click", function(e){
    e.preventDefault();
    var href = $(this).is("span") ? $(this).parent().attr("href") : $(this).attr("href");
    if ($("#listnameform").length){
	  $("#listnameform").unbind("submit").remove();
	  return false;
    }
    var listBox = "<form id='listnameform' class='listBox'><h3>Handleliste</h3>";
    listBox += "<label>Navn:<input type='text' id='listname' value='";
    listBox += $(this).attr('title') + "'></input></label><div class='button'><input class='submit'";
    listBox += " type='submit' value='Lagre'></input></div></form>";
    $(listBox).appendTo("body").center();
	$("#listnameform").bind("submit",function(event){
	    event.preventDefault();
	    customWebshopHandler({
		  "action" : "updateProductListName", 
		  "id" : href.substr(href.indexOf("id=")+3,10),
		  "name" : $("#listname").val()
		});

    });
	$("#listname").focus();
  });
  $(".savedCarts li a").live("click", function(e){ // load and rename
    e.preventDefault();
    var href = $(this).attr("href"),
        hid = href.substr(href.indexOf("id=")+3,10);
    if ($(e.target).is("span")){
      //customWebshopHandler({"action":"updateProductListName", "id":hid});
    } else if (ips.data.user.extra !== ""){
      customWebshopHandler({"action":"loadBasket", "id":hid});
    } else {
      confirm("Handlisten er ikke lagret. Er du sikker p\u00E5 at du vil overskrive?");
      customWebshopHandler({"action":"loadBasket", "id":hid});
    }
  });
  // make it possible to know when shoppingcarts gets merged with nulluser
  $("#loginForm").submit(function(e){
    if (ips.data.cart.length > 0) {
      var val = $(this).find("input[name=request]").val();
      var newVal = val + (val.indexOf("?") == -1 ? "?" : ";") + "merge=" + ips.data.cart.length;
      //console.log(newVal);
      $(this).find("input[name=request]").val(newVal);
    }
    return true;
  });
  $("#register").submit(function(e){
    if (!$("#joinNewsletter").attr("checked")) {
	  $("#groups").val($("#groups").val().substring(0,1));
    }	
    return true;
  });

var queue = ips.queue;
if (ips.queue) {
var ql = queue.length;
for (var j = 0;j < ql;j++) {
  var obj = queue[j];
  var cookie = $.cookie(obj.element);
  var $obj = $("#"+obj.element);
  if (cookie == 1) {
    $obj.html("<h2 class='timeMsg'>Du kan kun se bildet 1 gang og i " + obj.timer + " sekunder.</h2>");
    break;
  }
  $.cookie(obj.element,1,{ expires: 10, path: '/'});
  $obj.next().hide().end().prev().hide().prev().hide();
  $("div.button").hide();
  var $timer = $("<span class='timer'>"+obj.timer+"</span>").prependTo($obj),
      timer = obj.timer * 1000,
      startTime = new Date(),
      interval = setInterval(function(){
        var now = new Date();
        var timed = now - startTime;
        //console.log("Time! - " + timed);
        if(timed >= timer) {
          clearInterval(interval);
          $obj.hide("slow",function(){
            $(this).html("<p class='timeMsg'>Tiden er ute.</p>").show("slow");
            $obj.next().show("slow").end().prev().show("slow").prev().show("slow");
            $("div.button").show();
          });
        }
        $timer.text(Math.floor((timed / 1000) - (timer / 1000)));
      },1000);
  }
}

  var $joinNewsletter = $("input.joinNewsletter");
  if ($joinNewsletter.length) {
    $joinNewsletter.attr("checked","checked");

    $("form.quizContainer").submit(function(e){
      e.preventDefault();
      var $this = $(this),
          email = $("#_AID471_E-post").val();
      if (!emailpattern.test(email)) {
         $("#_AID471_E-post").addClass("error").focus();
         return false;
      }  
      if ($joinNewsletter.attr("checked")) {
        $.get(urlroot + "?template=xml&module=Users&action=UserGroup.publicAddEmailUserToGroup&newuser_groupid=4&id=4&lang=no&newuser_email=" + encodeURIComponent(email), function(data){
          $this.unbind("submit").submit();
        });        
      } else {
        $this.unbind("submit").submit();
      }


    });  
  }
 var $registerForm = $("#register");
 if ($registerForm.length) {
   $registerForm.submit(function(e){
	 var $this = $(this);
     $this.find("label").removeClass("error");
     var fields = $this.find("input.default").removeClass("error");
     fields.each(function(){
       if ($(this).val() == "") {
           $(this).focus().addClass("error").closest("label").addClass("error");
           e.preventDefault();
       }
     });
     var email = $this.find("#email").val();
     if (!emailpattern.test(email)) {
       $this.find("#email").addClass("error").prev("label").addClass("error");
       return false;
     } else {
       $this.find("#userName").val(email);
       return true;
     }
   });
  }
  var $forgotten = $("#forgotpassord"); 
  if ($forgotten.length) {
    var $passForm = $forgotten.find("#newPasswordForm");
    $forgotten.find("a").click(function(e){
      e.preventDefault();
      $passForm.toggle("slow");
    });
    $passForm.submit(function(e){
      e.preventDefault(); 
      startLoading("Genererer...");
      $.ajax({
       type : "POST",
       url : $(this).attr("action"),
       data: $(this).serialize(),
       success : function(){
         $passForm.toggle("slow");
         stopLoading("Passord sendt")
       },
        error : function(){
         $passForm.toggle("slow");
         stopLoading("En feil oppsto")
       }
     });
    });
  }
 // fix ie7 bug
 $(".imageWrapper img").live("click", function(){
    var $parent = $(this).parent().parent();
    if ($parent.is("a")) {
      window.location = $parent.attr("href");
    }

 });
 /*if (!$body.hasClass("minside")) {
    $(".minsideNav li:not(.current) img").css("opacity","0.5");
 }*/
 $(".externalLink").live("click", function(){$(this).attr("target", "_blank");}); 

function render(dataref) {
  var result = "<table class='tablesorter sort' style='width:100%;' id='result'><thead><tr><th>Poeng</th><th>E-post</th><th>Navn</th><th>Mobil</th></tr></thead><tbody>"
  $(dataref).each(function(){
    if ( (this.value1 !== undefined && this.value1 !== "") ) {
      result += "<tr><td>"+this.score+"</td><td>"+this.value1 +"</td><td>"+(this.value2 !== undefined ? this.value2 : "") + "</td>";
      result += "<td>" + (this.value3 !== undefined ? this.value3 : "") + "</td></tr>";
    }
  });
  result += "</tbody></table>";
  if ($("#result").length > 0) {
    $("#result").replaceWith(result);
  } else {
    $("#content").append(result);
  }
  $("#result").tablesorter();
}

$("a.getQuizWinners").click(function(e){
  e.preventDefault();
  var select = "values"+ $(this).attr("rel");
  //console.log(ips.data[select]);
  if (ips.data[select] === undefined) {
    startLoading("Laster");
    $.getJSON($(this).attr("href"), function(data){
      ips.data[select] = data[select];
      render(ips.data[select]);
      stopLoading("Ferdig laster");
    });
  } else {
    render(ips.data[select]);
  }
});

});
