// 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/basicpe/'
Req(
  'mobilefix', // <-- fixes rotation zoom bug in Mobile Safari, and scrolls page down to hide url bar...
  'eutils',
  'fontsizer',
  'autovalidate',
  'anchortags',
  'labelizor',
  'imgpop',
  'equalizeheights',
  'listscroller',

  function(){
    var $ = jQuery,
        body = $('body'),
        article = $('.article'),
        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').anchorTags({
                usePatterns:  ['doc', 'pdf', 'xls']
              })
            .filter('.external, .file_pdf, .file_doc, .file_xls')
                    .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+')')
                              .not(':has(img)')
                                  [useappend ? 'append' : 'prepend'](' <span class="icon">('+ text +')</span> ');
                        }
                      });

    } // end loggedin

    //sitemap collapser
    $('.sitemap').Req('treecollapse', function() { 
        $(this).treeCollapse({ 
            branch: 'li:has(ul)', 
            doTogglers: 1, 
            toggler: '> a.expand',
            startOpen: 'ul.level1 > li:has(ul)'
          }); 
        });
	
	
	// eq heights
	$('.twocol .pgextra2, .twocol .pgmain').equalizeHeights({margins:1});
	
	$('.home .col').equalizeHeights({margins:1});
	
	// toggle login click
	$('.loginform .boxhead').bind('click', function() {
		$(this).parent().toggleClass('active');
	});
	
	// inject shadow on more links
	$('.home .more a, .loginform .fi_btn').append('<div class="shadow"/>');
	
	// Events on frontpage
	
	$('.events .date').each(function(){
		var months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Okt', 'Nov', 'Des'];
		var eDate = $(this).text().replace(/\s{2,}/g, '').substring(0,2);
		var eMonth = $(this).text().replace(/\s{2,}/g, '').substring(3,5);
		
		$(this).html('<span class="day">'+ eDate +'</span><span class="month">'+ months[eMonth-1] +'</span>');
		
	});
	
	
	$('.events').listscroller({
	     item          : 'li',
	     windowSize    : 1,
	     stepSize      : 1,
	     startPos      : 1,
	     controls      : 'below',
	     labelNext     : '→',
	     overflow      : 'hidden',
	     labelPrev     : '←',
	     paging        : true,
	     animation     : 'crossfade'
	   });
	
	
	
	
	// Member - add more button since it doesn't appear with full articles
	$('.members .item').each(function() {
		var uri = $(this).find('h3 a').attr('href');
		
		$(this).find('.summary').append('<p class="moreolder"><a href="'+ uri +'">More</a></p>');
	});
				
				
					
	// Member fix for country and website
	
	$('.members .item').each(function () {
		var mCountry = $(this).find('.country').clone();
		var mWebsite = $(this).find('.website').clone();
		mWebsite.find('.icon').remove();
		//console.log(mCountry);
		
		$(this).append('<div class="sidebox"/>');
		$(this).find('.sidebox')
					.append(mCountry)
					.append(mWebsite);
	});
		
	
	//Search for members
	var sItems = $('.members .item');
	
	var searchList = function (country, searchtext) {
		
		var val = country + " " + searchtext;
		//console.log(val);
		if (val == "") {	
			
			sItems.removeClass("hide");	
			
		 }	else {
			 	
			sItems.removeClass("hide");
		 			 		
	 		var searchString = val.trim();
	 		var searchRe = new RegExp("(?:"+ searchString.replace(/\s+/g, "|") + ")", "gi");
	 	  
	 		sItems.each(function(e) {
	 			var st = $(this).text();
	 			var match = 0;
	 	
	 			if (searchRe.test(st)) { 
	 				// Do stuff to matched elements
	 				
	 			} else { 
	 				//Do stuff if element doesn't match
	 				$(this).addClass("hide");
	 			}
	 		});
		 }
	}
	
	
	// Find unique countries	
	var mArray = [];
	var mObject = {};
	
	$('.country').each(function (){
		var country = $(this).text().trim();
		
		if ( !mObject[country] ) {
			mArray.push(country);	
		} 
		mObject[country] = country;
	});
	
	mArray = mArray.sort();
	
	// Populate select box with countries
	for (i = 0; i <= mArray.length-1; i++) { 
		$('#catfilter').append('<option value="'+ mArray[i] +'">'+ mArray[i]+'</option>');
	}
	
	
	//Filter list based on search terms
	$("#catfilter").change( function () {
		searchList($('#catfilter').val(), $('#filtersearch').val());
		console.log('searching country');
	});
	
	$("#filtersearch").keyup( function () {
		searchList($('#catfilter').val(), $('#filtersearch').val());
	});
	
	
	
	
	
	
	
    //remove flicker trick
    $('#noFOUC-main').remove();

    // fontsizer
    $('.pagestyle').fontsizer();

    // validate all forms
    $('form').autoValidate();

    //loading body class scripts 
    Req.loadPageScripts({ folder:'' });

  }
);
// **** /jqreq *****

