// encoding: utf-8
/*@cc_on/*@if(@_jscript_version<5.7)try{document.execCommand('BackgroundImageCache',0,1)}catch(e){}/*@end@*/

// ***** jqreq *****
Req.localPath = Req.localPath || '/skin/basic/';
Req(
  'eutils',
  'fontsizer',
  'autovalidate',
  'anchortags',
  'labelizor',
  'imgpop',
  'fickle',

  function(){
    var $ = jQuery,
        body = $('body').addClass('js-active'),
        article = $('.article, .articlelist .summary'),
        msie =   $.browser.msie   &&  parseInt($.browser.version,10)<9;  // or: $('html').is('.msie');

    var texts = {
        is: {
            newWindow:        'Opnast í nýjum vafraglugga',
            fileText:         'skjal'
          },
        en: {
            newWindow:        'Opens in new window',
            fileText:         'file'
          }
      };
    texts = texts[ $.lang() ]  ||  texts.en;

    // labelize search input
    $('#qstr').labelizor();

    if (!window.EPLICA_loggedin)
    {

      //zebra tables
      $('tbody tr:nth-child(2n-1)').addClass('odd');
      //$('tbody tr:nth-child(2n)').addClass('even');


      //popup in articles
      article.find('.imagebox a.img')
          .each(function() {
            var imgsrc = $(this).find('img').attr('src').replace(/\/[^\/]+\/([^\/]+)$/, '/large/$1');
            $(this).attr('href', imgsrc)
          })
          .imgPopper({
              curtainColor : '#ffffff',
              curtainOpacity : '0.75',
              yOffset: 15
            });


      article.find('a.videolink').Req(
          'q-videolinks',
          function() {
            $(this).videoLinks(); //{ vidWidth:'auto',vidHeight:'auto',aspect4x3:false }  Set width and height (default auto) and aspect 4x3 autocalc (default 16x9)
          }
        );


      //tag external urls
      var link, text, useappend, match;
      $('a').not('.videolink').anchorTags({
                usePatterns:  ['doc', 'pdf', 'xls']
              })
            .filter('.external, .file_pdf, .file_doc, .file_xls')
                .not(':has(img)')
                    .each(function() {
                        link = $(this);
                        text = '';
                        useappend = false;
                        match = this.className.match(/(^| )file_([a-z]+)( |$)/);
                        if ( match )
                        {
                          text = match[2].toUpperCase() +' '+ texts.fileText;
                        }
                        else if ( $(this).is('.external') )
                        {
                          text = texts.newWindow;
                          useappend = true;
                        }
                        if (text)
                        {
                          link
                              .attr('target', '_blank')
                              .attr('title', (link.attr('title')||link.text()) +' ('+ text+')')
                              [useappend ? 'append' : 'prepend'](' <span class="icon">('+ text +')</span> ');
                        }
                      });
                      
      
      // headings with blue last word
      
      $('.bloglist h3 a, .article h1')
          .each(function(){
            
              $(this).html( this.innerHTML.replace(/(\w+)\s*$/, '<span>$1</span>') );
            
          });
          
      
      // social networks buttons
          
      $('.article .boxbody')
          .each(function(){
            
              var title = $(this).find('h1').text();
            
              $(this)
                  .append('<div class="share">' +
                            '<a class="facebook" href="http://www.facebook.com/sharer.php?u='+ window.location.href +'&t='+ title +'">Facebook</a>' +
                            '<a class="twitter" href="http://twitter.com/home?status='+ title +': '+ window.location.href +'">Twitter</a>'+
                          '</div>');
            });
          
                      
                                           

    } // end loggedin
    
    
    // adverts
    
    $('.pgextra3 .advert a')
        .each(function(){
            
            var a = $(this),
                i = a.find('img');
          
            i.css('margin-top', parseInt(((a.height() - i.height()) / 2), 10) + 'px'); // middle the adverts
          
          });
          
          
    // eventlist
          
    $('.eventlist .item')
        .bind('click', function(){
          
            window.location = $(this).find('h3 a').attr('href');
            
          });
          
    
    
    // galleryintro
          
    $('.galleryintro')
        .each(function(){
          
            var boxhead = $(this).find('.boxhead').hide();
          
            $(this)
                .find('.boxbody a')
                .append('<span>' + boxhead.text() + '</span>');
                
          
          });
          
    
          
    // designer
    
    $('.designers .item')
        .each(function(i){
          
            var imgbox = $(this).find('.imagelist');
            var morehref = $(this).find('.more a').attr('href');
            var header = $(this).find('h1, h3').hide().eq(0).text();
          
            
          
            var bigimg = imgbox.before('<div class="bigimg" />').parent().find('.bigimg');
          
          
            imgbox
                .find('a')
                    .bind('click', function(){
                      
                          bigimg.html('<a href="'+ morehref +'"><img src="' + $(this).attr('href') + '" alt="" /> <span>' + header +'</span></a>');
                      
                          return false;
                      
                      })
                      .eq(0).click(); // firstrun
                      
          
            if(i % 3 == 0) {
              
              $(this).addClass('first-in-row').before('<div class="sep" />');
              
            }
            
          
          });
          
          
        
    
    // Google maps (goes with the "article about" bit)
    
    var aboutheight = $('.about').height();
    var mapCanvas = $('#map_canvas').css('height', (aboutheight + 45) + 'px');
    
    if (mapCanvas.length)
    {
      // Google maps
      
      var dotpos = new google.maps.LatLng(47.67764,-122.396793),
          latlng = new google.maps.LatLng(47.678824,-122.40263),
          myOptions = {
            zoom: 16,
            center: latlng,
            disableDefaultUI: true,
            mapTypeId: google.maps.MapTypeId.SATELLITE
          },
          map = new google.maps.Map(mapCanvas[0], myOptions),
          marker = new google.maps.Marker({
                      position: dotpos,
                      map: map, 
                      title:"Nordic Heritage Museum"
                    });
    }
    
    
    
    // mediagallery

    $('.albums li')
        .each(function(){
          
            $(this).find('.count').appendTo($(this).find('a'));
          
          });
          
    $('.singleimage')
        .each(function(){
          
            $(this).find('.boxhead').append(' <i>-</i> <span class="current">' + $(this).find('.imgname').hide().text() + '</span>');
          
          });
          
    $('.mediagallery')
        .each(function(){
          
            var pagestat = $(this).find('.pgs');
          
            if(pagestat.length) {
              
              $(this)
                  .find('.boxhead')
                      .append('<small class="pgs">:'+ pagestat.hide().html() +'</small>');
              
            }
                
          
          });
    
    

    //sitemap collapser
          
    $('.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });
        
        
	// validate all forms
	$('form').autoValidate();
	
	//form modal thanks window
	var contestForm = $('.contactform form');
	var contestAction = contestForm.attr("action");
	contestForm.bind('submit', function(e) {
		var result;
		
		if (!e.isDefaultPrevented()) {
					
					$.post(contestAction, $(this).serialize(), function(data) {
						result = $(data).find('.article.box');
			
						var curtain = $('<div class="contest-result curtain"><div class="modal"><a class="focustarget" href="/">.</a>'+ $(result).html() + '</div></div>');
						
						curtain.appendTo('body');
						
						curtain.fickle({
						    focusTarget: null,
						    fadein: 350,
						    fadeout: 200,
						    onOpen:   function (e) { $('.contest-result .modal').css({ top: $(window).scrollTop() }) },
						    onClose:  function (e) {  },
						    onClosed: function (e) { $(this).remove() }
						  })
						  .bind('click', function (e) {
						  	  if ( this==e.target  ||  $(e.target).closest('a.closebtn')[0] )
						  	  {
						  	    $(this).fickle('close');
						  	    if ($(this).find("div:contains('John')")) {
						  	    	 
						  	    	 console.log("ERROR");
						  	    	 window.location.reload();
						  	    }
						  	  }
						    })
						  .fickle('open', { opener: contestForm });
						
						
					});
			
		
			return false;
		}
				
	})
	        

    //remove flicker trick
    $('#noflickerCSS').remove();

    // fontsizer
    $('.pagestyle').fontsizer();

  

    //loading body class scripts 
    Req.loadPageScripts();

  }
);
// **** /jqreq *****

