/**
 * @author redstuff
 */
// MASTER JS
// SWFobject for IPS by sveinung@idium.no Feb 2010
(function f(b){var d=window.ips=window.ips||{},c=b||{loading:false},e;if(d.queue===undefined)d.queue=[];if(typeof window.swfobject!=="undefined"&&typeof window.swfobject.embedSWF!=="undefined")c.loading=false;else if(d.queue.length>0){if(c.loading===false){b=document.createElement("script");b.type="text/javascript";b.async=true;b.src="http://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js";(document.getElementsByTagName("head")[0]||document.getElementsByTagName("body")[0]).appendChild(b); c.loading=true}e=setTimeout(function(){f(c)},50)}if(c.loading===false&&d.queue.length>0)for(b=0;b<d.queue.length;b++){var a=d.queue[b];if(!a.loaded){a.loaded="true";swfobject.embedSWF(a.url,a.element,a.width,a.height,a.version,a.expressInstall,a.flashvars,a.params,a.attributes)}}if(c.loading===false&&typeof window.jQuery!=="undefined")e=setTimeout(function(){jQuery(document).one("ajaxStart",function(){e=setTimeout(function(){f(c)},100)})},2E3)})();
//master.js
jQuery(document).ready(function($) {

	//Slideshow 2 
	slideShow();

	function slideShow() {
		//new setting
  

		//Set the opacity of all images to 0
		$('#gallery2 a').css({opacity: 0.0});

		//Get the first image and display it (set it to full opacity)
		$('#gallery2 a:first').css({opacity: 1.0});

		//Set the caption background to semi-transparent
		//$('#gallery2 .caption').css({opacity: 0.7});

		//Resize the width of the caption according to the image width
		$('#gallery2 .caption').css({width: '438px'});

		//Get the caption of the first image from REL attribute and display it
		$('#gallery2 .content').each(function() {
                  $(this).html($('#gallery2 a:first').find('img').attr('rel'));
    $('.caption h6').click(function() {
      var linktoarticle = $('.show').attr('href');
      window.open (linktoarticle,'_self',false)
    });
                });


		//.animate({opacity: 0.7}, 400);

		setInterval(function() {
	       	//if no IMGs have the show class, grab the first image
		var current = ($('#gallery2 a.show')?  $('#gallery2 a.show') : $('#gallery2 a:last'));

		//Get next image, if it reached the end of the slideshow, rotate it back to the first image
		var next = ((current.next().length) ? ((current.next().hasClass('caption'))? $('#gallery2 a:first') :current.next()) : $('#gallery2 a:first'));	

		//Get next image caption
		var caption = next.find('img').attr('rel');	
                

		//Set the fade in effect for the next image, show class has higher z-index
		next.css({opacity: 0.0})
		.addClass('show')
		.animate({opacity: 1.0}, 1000);

		//Hide the current image
		current.animate({opacity: 0.0}, 1000)
		.removeClass('show');

		//Set the opacity to 0 and height to 1px
		$('#gallery2 .caption').animate({opacity: 0.0}, { queue:false, duration:0 }).animate({height: '1px'}, { queue:true, duration:300 });	

		//Animate the caption, opacity to 0.7 and heigth to 100px, a slide up effect
		$('#gallery2 .caption').animate({opacity: 1},100 ).animate({height: '50px'},500 );

		//Display the content
		$('#gallery2 .content').html(caption);   
	    }, 11000);

		//Call the gallery function to run the slideshow, 6000 = change to next image after 6 seconds
		//setInterval('gallery()',6000);

	}

  $('#s5').cycle({ 
    fx:     'scrollHorz', 
    prev:   '#prev1', 
    next:   '#next1', 
    timeout: 0, 
    before:  onBefore, 
    after:   onAfter 
 });

function onBefore() { 
    //$('#output').html("Scrolling image:<br>" + this.src); 
} 

// Link to title on automatic slideshow

function onAfter() { 

    /*$('#output').html(this.alt); */

    var url = $('.slideshow_image_file').attr('href');
    $('#output').html(
      '<a href="'+
      url+
      '">'+
      $(this).children('img').attr('alt')+
     '</a>'
    );
}


  $("div.paging").quickPager();

   // OBJECT COMMENTS
   //TODO  : make it more than just work...
   $("ul.comments").load(ips.system.base + "?module=ObjectComments&action=ObjectComments.getCommentsForObject&className=articles.Article&template=esicomments&onlyApproved=false&objectID=" + $(this).attr('title'));
   // END OBJECT COMMENTS

   // UTILITY
   var base = ips.system.base; //cache as local variable
   // INLINE editing activation

   // Searchform interaction
   var $searchForm = $("#searchForm"), //CACHE
       $query = $searchForm.find(".query"),
       $label = $searchForm.find("label");
   if ($query.val() !== "") {$label.hide()}
   $searchForm.submit(function(){
   if ($query.val() === "") {return false}
   });
   $query.focus(function(){$label.hide()}).blur(function(){
     if ($(this).val() === "") {$label.show()}
   });
   $searchForm.find("label").click(function(){
    $query.focus();
   }); 
   // END SEARCHFORM



var gallery = $('#gallery').galleriffic('#thumbs', {
    delay:                    2000,
    //numThumbs:                5,
    imageContainerSel:        '#slideshow',
    controlsContainerSel:    '#controls',
    enableTopPager:           false,
    enableBottomPager:        false,
    //titleContainerSel:      '#image-title',
    //descContainerSel:       '#image-desc',
    //downloadLinkSel:        '#download-link',
    fixedNavigation:          false,
    galleryKeyboardNav:       true,
    autoPlay:                 false
  });
  
  gallery.onFadeOut = function() {
    $('#details').fadeOut('fast');
  };
  
  gallery.onFadeIn = function() {
    $('#details').fadeIn('fast');
  };





// IPS FORM validation by sveinung@idium.no March 2010
$("form").live("submit",function(e){
    var $this = $(this), formid = $this.attr("id")+"", errors = [];
    // Start validation object
    //fix broken objects
    var ips = window.ips = window.ips ||{};
    ips.validate = ips.validate ||{};
    ips.validate[formid] = ips.validate[formid] ||{};
    //end fix broken objects

    // Reset, and FIND/QUERY viable <li> tags. Must be typical <li> with input. If different, change next find().
    $this.find("span.error").remove().end().find("li:not(.submit,.form_labelfield)").removeClass("error")
    // START each - > iterate li`s
    .each(function(i){
      // Needed vars and Cache selectors for convenience and "speed"
      var $li = $(this), $nextLi = $li.next(), $prevLi = $li.prev(), $field = $li.find("input,textarea,select").eq(0), fid = $field.attr("id"), fieldval = $field.val(), errorObj = {"id":fid,"$elem":$li,"message":""};
      // Utilty function for checking regex values
      var checkFunc = function(regexObj, thisval, message, errorObj){
        if (!regexObj.test(thisval)) {
           errorObj.message = message;
        } else {
           errorObj.valid = true; // used to make this rule more important than classes
        }
        return errorObj;    
      }
      // Iterating and validation all regexes in the general object
      $.each(ips.validate.general, function(property){
        if ($li.hasClass(property) && this.regex !== undefined ) {
          errorObj = checkFunc(this.regex, fieldval, this.message, errorObj);
        }
      });
      // Check for validation object
      if ( ips.validate[formid][fid] !== undefined && ips.validate[formid][fid].regex !== undefined ) {
         var fieldvalObj = ips.validate[formid][fid],
             errorMgs = fieldvalObj.message !== undefined ?  fieldvalObj.message : ips.strings.notvalid;
         errorObj = checkFunc(new RegExp(fieldvalObj.regex), fieldval, errorMgs, errorObj);
      } else {
        //fix missing objects
        ips.validate[formid][fid] = {};
      }
      if ( $li.hasClass("form_password") && errorObj.message === ''){
          errorObj = checkFunc(ips.validate.general.password.regex, fieldval, ips.validate.general.password.message, errorObj);
          if (errorObj.message === "" && fieldval !== $li.find(".confirm").val()) {
            errorObj.id = $li.find(".confirm").attr("id");
            errorObj.message = ips.validate.general.password.message;
          }
      }
      // Check username if form has class .loggedout -> Forms get resubmitted if error from server
      if ( $this.hasClass("loggedout") && $li.hasClass("username") && !(errorObj.valid)){
          var searchedUsername = $.data($field[0],"username"), // get "cacge"
              availFromPrevSubmit = $.data($field[0],"avail"); // get "cache"
          $.data($field[0],"username",fieldval); // write "cache"
          // Check if new desired username isnt equal to previous ones or if no username has been checked
          if ((fieldval !== searchedUsername) || (availFromPrevSubmit === null) ) { 
            // Async - check param, then set value on elem and resubmit form
            $.get(ips.system.base + "?module=Users&amp;action=Ajax.isUsernameAvailable&amp;username="+fieldval, function(data){
               $.data($field[0],"avail",data);
               // 'false' is serverresponse in plain text
               if (data == 'false') {
                 setTimeout(function(){$this.submit();},100);
               }
            });
          } else {
            // check if this is checked and username is not avail === false
            if (availFromPrevSubmit == "false") {
              errorObj.message = ips.strings.usernamenotavail;  
            }  
          }
      }
      // check if .required and 
      if (fieldval === '' &&  $li.hasClass("required")) {
          // If not already a error - add a error message
          if (errorObj.message === '') {
            errorObj.message = ips.strings.cannotbeempty;
         }
      } else if ($li.hasClass("required") && errorObj.message === '') {
          // if checkbox is required
          if ($field.is("input[type=checkbox]") && $field.attr("checked") === false) {
            errorObj.message = ips.validate[formid][fid].message ||ips.strings.mustbechecked;
          }
      }
      // Todo, ADD : requiredIf - (e.g. email, checkbox )
      // Check for customclasses 'isequaltonext' and 'isequaltoprev' - > is in lowercase bacause of ips:classify
      if ($li.hasClass('isequaltonext')||$nextLi.hasClass('isequaltoprev')) {
        if (fieldval !== $nextLi.find("input").val()) {
          errorObj.message = $li.find("label").text() + ips.strings.mustbeequalto + $nextLi.find("label").text();
        }
      } else if ($li.hasClass('isequaltoprev')||$prevLi.hasClass('isequaltonext')) {
        if (fieldval !== $prevLi.find("input").val()) {
          errorObj.message = $li.find("label").text() +  ips.strings.mustbeequalto + $prevLi.find("label").text();
        }
      }
      // Field is not required, NO error-msg should be generated
      if (fieldval === '' && !($li.hasClass("required"))) {
          errorObj.message = ''; 
      }
      // Push this errorObj if there is a message defined
      if ( errorObj.message !== undefined && errorObj.message !== '' ) {
        errors.push(errorObj);
      }
    }); //END each li`s

  // Process errors if there is any
  if ( errors.length > 0 ) {
    $( errors ).each(function(i){
      var $errorField = this.$elem.addClass("error").find("input,textarea,select").eq(0);
      if (i === 0) {;$errorField.focus();}
      $("<span class='error'>" + this.message + "</span>").insertAfter( $errorField );  
    });
    // default action of the event will not be triggered.
    e.preventDefault();
    // Keeps the rest of the handlers from being executed.
    e.stopImmediatePropagation();
  } else {
	$this.find("input[type=submit]").val("Sender...");
}
});
//FORM END

// TOGGLE
$(".toggle").not("a").hide();
$("a.toggle").click(function(){
$(this).next(".toggle").toggle("slow");
return false;
}); //END TOGGLE 

// TIPS FORM
  var $tipsform = $("#tipsForm").submit(function(event){
    var $this = $(this), $senderName = $("#senderName"), $senderEmail = $("#senderEmail"), $recipientEmail = $("#recipientEmail"), $response = $this.find("h3");
    $this.find(".error").removeClass("error");
    if($senderName.val() === "") {
        $senderName.addClass("error").focus().parent().addClass("error");
        return false;
    }
    if(!emailpattern.test($senderEmail.val())) {
        $senderEmail.addClass("error").focus().parent().addClass("error");
        return false;
    }
    if(!emailpattern.test($recipientEmail.val())) {
        $recipientEmail.addClass("error").focus().parent().addClass("error");
        return false;
    }
    $.ajax({
          url: urlroot,
          data: $tipsform.serialize(),
          error: function() {
            $response.text("FEIL");
          },
          success: function() {
            $response.text("Tipset ble sendt!");
            $tipsform.toggle("slow");
          }
     });
     return false;
   });


  /* Mouseover on images, setup relattribute on FILE match */
  $("img.hover").live("hover", function(){
    var _alt = $(this).attr("alt"), _src = $(this).attr("src");
    $(this).attr("src",_alt).attr("alt",_src);
  });


});  /* Document end */


jQuery(window).load(function(){
    function equalHeight(group) {
	tallest = 0;
	group.each(function() {
		thisHeight = $(this).height();
		if(thisHeight > tallest) {
			tallest = thisHeight;
		}
	});
	group.height(tallest);
    }

    function equalWidth(group) {
	widest = 0;
	group.each(function() {
		thisWidth = $(this).width();
		if(thisWidth > widest) {
			widest = thisWidth;
		}
	});
	group.width(widest);
    }
    //Readjust height after images have loaded.
    equalWidth(jQuery(".sameWidth"));
    equalHeight(jQuery(".sum"));
    equalHeight(jQuery(".summary.fp .summary"));
    equalHeight(jQuery(".sameheight"));
});
