var isFrontpage = false;
var int;
var int2;
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 isValidEmailAddress(emailAddress) {
 		var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
 		return pattern.test(emailAddress);
	}

/***** ******/

$.fn.wait = function(time, type) {
     time = time || 1000;
     type = type || "fx";
     return this.queue(type, function() {
         var self = this;
         setTimeout(function() {
             $(self).dequeue();
         }, time);
     });
};


jQuery(document).ready(function($){

var isIE = navigator.userAgent.indexOf("MSIE") == '-1' ? false : true;
//if(isIE) $("body").addClass("ie7");




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


if($(".summary").length>16) {
  var elementCount = $(".summary").length;
  var pagecount = Math.ceil(elementCount/28); //  number up to the nearest upper integer
  $('#content').evtpaginate({perPage:28});
  var paginationHtml = "<ul class='pagination'></u>";
  $("#content").append(paginationHtml).prepend(paginationHtml);
  for(x=1;x<(pagecount+1);x++) {
    $(".pagination").append("<li><a href='#"+x.toString()+"'>"+x.toString()+"</a></li>");
  }

$(".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');
  }
}


if(!$("#searchForm2 input[name='query']").val().length) // there is no query
  $(".query").Watermark("Gj\u00F8r et produkts\u00F8k","#CCC");
else{
  $(".query").val($("#searchForm2 input[name='query']").val().replace("(","").replace(")AND(attribArticleType:Produkt)",""));
  $(".pagination li a").each(function(){
    if($(this).text().length > 1)
      $(this).css({background:'url('+urlroot+'filestore/dev/GFX/paginator-li-bg-double.png) no-repeat'});
  })
   
}
$("#newsletterForm input[type=text]").Watermark("Nyhetsbrev p\u00E5 e-post","#CCC");
/*
$(".query").Watermark("Gjør et produktsøk");
$("#newsletterForm input[type=text]").Watermark("Nyhetsbrev på e-post");
*/

if($(".pagination li").length < 3) $(".pagination li.active").hide();



var thislocation = window.location.pathname;
var imgfolder = urlroot+'filestore/dev/GFX/';

/*
if(window.location.toString()==urlroot) { 
  var toOpacity = 1, duration = 8000; 
  $("#backgroundimage").fadeTo(duration,toOpacity); 
  $("#backgroundimage").fadeTo(duration,toOpacity);
}
else {
  var toOpacity = 1, duration = 20; 
  $("#backgroundimage").fadeTo(duration,toOpacity);
}

*/
  var toOpacity = 1, duration = 20; 

if(!isFrontpage)
  $("#backgroundimage").fadeTo(duration,toOpacity);


$("#header").click(function(){
  window.location.replace(urlroot);
});

var x = 1; // initialize

// folder for background images used for the products menu
var pfolder = imgfolder+'produkterbg/';

// color used in the products menu :
var colorArray = ["","#562C61","#E3BF04","#FF4F00","#FF0000","#000000","#0096D5","#00A42D","#583019","#F9006A","#766B64"];

$("#navProducts li a").each(function(){
  $(this).css({background:'url('+pfolder+'p'+x+'_2.png) repeat-x '})/*.attr("rel",colorArray[x])*/; // store color in rel for later use (or don't)
  $(this).append('<img src="'+pfolder+'p'+x+'_1.png" class="leftcorner"><img src="'+pfolder+'p'+x+'_3.png" class="rightcorner"><span>&#62;</span> ');
  if(x<10)x++;
  else x=1; // loop colors
});

// color products title is not in use anymore
//var currentproduct = $("#navProducts li a.current");
//if(currentproduct.length)
//$("#infoAndSubNav h1").css("color",currentproduct.attr("rel"));

$('#questionmark').qtip({
   content: $(".nhcContent").html(),
   show: 'mouseover',
   hide: 'mouseout',
   style: { 
      name: 'blue', // Inherit from preset style
      tip: 'topRight',
      width: 300
   },
   position: {
      corner: {
         target: 'leftMiddle',
         tooltip: 'topRight'
      }
   }

});

$('#imagesthumbs li a').lightbox({fixedNavigation:true});

if(!$("#imagesthumbs li:not(.second)").length) { // there is only one image for this product
  $("#imagesthumbs").hide(); // hide thumbs for main image, it's useless when there only is one
}
$("#imagesthumbs li a").bind("mouseover",function(){
  var bigHref = $(this).attr("href");
  var mediumHref = bigHref.replace("?size=900x700","?size=210x150");
  $("#relatedImages li a").attr({href:bigHref}).children("img").attr({src:mediumHref});
  clearInterval(int2);
  interval2();

/*setTimeout("var imgwidth = $('#relatedImages li a img').width();var imgheight = $('#relatedImages li a img').height();$('#loupe').css({left:imgwidth-25+'px',top:imgheight-26+'px'});",250);
*/
});


$("#relatedImages li a").click(function(e){
  e.preventDefault();
  var href= $(this).attr("href");
  $("#imagesthumbs li a[href="+href+"]").click(); // a click on the big image is like a click on the matching thumbnail. Done so to maintain order of images in jquery lightbox slideshow
});

if($("#productMainColumn").length) {
 // nothing for now
}

$(".tipEnKollega,.cross").click(function(e){
  e.preventDefault();
  $("#tipsbox").toggle();
});



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


// LAST PRODUCTS VIEWED IN COOKIE 

$("body").bind("loadCookie", function(){
        ips.data.history = [];
		var loadCookie = $.cookie("history") || '';
        var cookie = loadCookie !== '' ? $.secureEvalJSON(loadCookie) : null ;
        if (typeof cookie === "object" && cookie !== null) {ips.data.history = cookie;}
        var historyLength = ips.data.history.length;
        var productPage = $("#productMainColumn").length;
        if (historyLength && productPage) {
            var items = "";
            for (var j = 0;j < historyLength; j++) {
                if (ips.data.history[j] && ips.data.history[j] !== null) {
                  items += "<li><a href='"+ ips.data.history[j].url+"'>" + ips.data.history[j].name + "</a></li>";
                }
            }
            $("<div id='lastViewedProducts'><h3>Sist sette produkter</h3><ul id='navHistory' class='nav'>"+ items + "</ul></div>").appendTo("#leftColumn");
        } 
        var newArray = [];
        if ($("#productMainColumn").length) {
            var sitetitle = document.title + ""; // gets window title
            var name = sitetitle.substring(0,sitetitle.indexOf(":")); // gets windowtitle, and gets navigated part before ":"
            var isUnique = true; // var for checking if unique
            for (var h = 0;h < historyLength; h++) {
                if(ips.data.history[h] && ips.data.history[h] !== undefined && ips.data.history[h].name === name) {
                    isUnique = false;
					break;
                }
            }
            if (h === 0 && ips.data.history[1]) {
				newArray[0] = ips.data.history.splice(0, 1)[0];
			}  else if (isUnique) {
                newArray[0] = {"name":  name , "url": window.location+"" };			
			}  else if (!isUnique){
				newArray[0] = ips.data.history.splice(h, 1)[0];		
			}
			newArray[1] = ips.data.history[0];
			newArray[2] = ips.data.history[1];
			newArray[3] = ips.data.history[2];
			newArray[4] = ips.data.history[3];
            $.cookie('history', $.toJSON(newArray), { expires: 100, path: '/'});
        } 
    }) // end event
    .trigger("loadCookie"); // trigger  event on body

if($(".custome1-user-table").length) { // set cross-browser css3 selectors 
  $(".custome1-user-table tbody tr:first").addClass("first");
  $(".custome1-user-table tbody tr").each(function(){
    $(this).children().first().addClass("first");
    $(this).children().last().addClass("last");
  });  
}

if(!$("#relatedImages .first a img").length) {
  $("#productImageMedium").hide(); //
}

$(".skrivUt").click(function(e){
  e.preventDefault();
  window.print();
});

 $("#newsletterForm").submit(function(e){
     e.preventDefault();
     if(isValidEmailAddress($(this).find("fieldset input[type='text']").val())) {
       $.post($(this).attr("action"),$(this).serialize())
       $(this).children("span").remove();
       $(this).append("<span>Du vil mota v&#229;rt nyhetsbrev</span>");
   }
     else {
       $(this).children("span").remove();
       $(this).append("<span><strong>Epostadressen er feil</strong></span>");
     }
 });

$("#searchForm").submit(function(e){
  e.preventDefault();
  $("#searchForm2 input[name='query']").val('('+$(".query").val()+')AND(attribArticleType:Produkt)');
  //$(this).unbind();
  $("#searchForm2").submit();
});

$('#loupe').one('positionLoupe',function(){
   imgwidth = $('#relatedImages li a img').width();
   imgheight = $('#relatedImages li a img').height();
   $('#loupe').css({left:imgwidth-25+'px',top:imgheight-26+'px',cursor:'pointer'},250).click(function(){$(this).prev().click();});
   clearInterval(int);
});

$('#loupe').bind('repositionLoupe',function(){
   imgwidth = $('#relatedImages li a img').width();
   imgheight = $('#relatedImages li a img').height();
   $('#loupe').animate({left:imgwidth-25+'px',top:imgheight-26+'px'},250);
   clearInterval(int2);
});

var interval2 = function() {
  
int2 = setInterval("if($('#relatedImages li a img').width()>0)$('#loupe').trigger('repositionLoupe');",350);
}


if($("#relatedImages li a img").length) {
int = setInterval("if($('#relatedImages li a img').width()>0)$('#loupe').trigger('positionLoupe');",50);
}

});
