/* 
* This is where all the Seedose.at custom javascript goes 
* Author: Martin Grubinger
*/

var template_url = "http://www.seedose.at/wp-content/themes/seedose/";
var bg_path = template_url + "images/background/";
var view_background_duration = 300;      // duration of wrapper fade out
var backslide = 0;                      // initial backgroundimage index

$(document).ready(function() {
  // change default easing function to 
  //jQuery.easing.def = "easeInOutQuart";

  initBackstretch();
  
  $('.fbphotos a').nyroModal();
  
  if($("#tec-content").length > 0) $(".page-item-17").addClass('current_page_item');
  
  getGalleryPageThumbs();

  initNewsletterToggle();
  
});


function initBackstretch() {
  // read backslide cookie if exists
  var backslide_cookie = readCookie("backslide");
  if(backslide_cookie) backslide = backslide_cookie;
  $(".background_control_button").eq(backslide).addClass("active");
  
  // show backstretch controls container
  $("#backstretch_wrapper").show();
  
  // handle toggle button ("photos")
  $("#backstretch_button").toggle(
    function(event) {
      event.preventDefault();

      $("#wrapper").fadeOut(view_background_duration);
      
      $(".background_control_button").fadeTo(10,0);
      $("#background_controls").css("width", "1px").show().animate({
        width: 86,
        paddingLeft: 12
        }, 250, function() { 
          $(".background_control_button").fadeTo(100,1);
          $("#backstretch_button").addClass("active");
        }
      );
    },
    function(event) {
      event.preventDefault();

      $("#wrapper").fadeIn(view_background_duration);     
      
      $(".background_control_button").fadeTo(100,0, function() {
        $("#background_controls").animate({
          width: 0,
          paddingLeft: 0
        }, 250, function() { 
            $("#backstretch_button").removeClass("active");
          }
        );
      });
    }
  );
  
  
  // handle select bg buttons
  $(".background_control_button").bind("click", function() {
    
    // lock for further interaction to avoid problems through rapid clicking
    if($("#backstretch").not(":animated").length > 0) {
      var index = $(".background_control_button").index($(this));
      
      if(index != backslide) {
        // switch background image
        backslide = index;
        
        $("#ajaxloader_container").show();
        $("#backstretch_button").removeClass("active").addClass("blank");
        
        var i = new Image();
        // when image is done loading, show it
        $(i).bind("load", function() {
          $("#ajaxloader_container").hide();
          $("#backstretch_button").removeClass("blank").addClass("active");
          $("#backstretch").clone().attr("id", "backstretch-2").find("img").addClass("new").parent().prependTo($("body"));
          $("#backstretch-2 img").attr("src", bg_path + "bg0" + backslide + ".jpg");
          
          $("#backstretch").fadeOut(500, function() { 
            $(this).remove(); 
            $("#backstretch-2 img.new").removeClass("new");
            $("#backstretch-2").attr("id", "backstretch");
          });
          $(i).unbind("load");
        });
        
        // now load the image
        i.src = bg_path + "bg0" + backslide + ".jpg";
        
        $(".background_control_button").removeClass("active");

        $(this).addClass("active");
        
        createCookie("backslide", backslide, 30);
      }
    }  
  });
  
  // load & display backstretch image
  $.backstretch(bg_path + "bg0" + backslide + ".jpg", {speed: 0});
  
}

/*
 * Function to set the border on the navigation
 * if scrolled further down
 */
window.onscroll = function handleScrolling() {
  var scrollingPos = new Array();
  scrollingPos = $(window).scrollTop();
  if(scrollingPos > 300) {
    $("#navigation").addClass("scrolling");
  } else if($("#navigation").hasClass("scrolling") == true) {
    $("#navigation").removeClass("scrolling");
  }

};


/* 
 * getGalleryThumbs: 
 * Load the contents of galleries-page.php
 * asynchronously. This script is only for 
 * the gallery page, in the plugin folder js is a modified one for
 * the widget.
 */
function getGalleryPageThumbs() {
  
    // get facebook ids from html
    $(".gallery_list .gallery_thumbnail a").each(function() {

        // set the class to loading to show loading indicator
        $(this).parent().removeClass("ajaxerror").addClass("loading");
    
        var fbid = $(this).attr("rel");

        // send AJAX request and process data#

        $.ajax({
            type: "GET",
            url: 'wp-content/plugins/seedose/galleries.php',
            data: "fbid=" + fbid,
            success: function(xml) {

                var count = $(xml).find("count").text();
                var thumb = $(xml).find("th").text();

                var img = new Image();

                // append new image to thumbnail container and set the src
                var this_gal = $('.gallery_thumbnail a[rel="' + fbid + '"]');
                this_gal.append(img).parent().removeClass("loading");

                img.src = thumb;

                $(img).bind("load", function() {
                    var gt_height = $('.gallery_thumbnail').height();
                    var img_height = $(this).height();
                    var offset_y = (gt_height - img_height)/2;
                    $(img).css("margin-top",offset_y);
                    img.css("visibility", "visible");
                    $(this).unbind("load");
                });

                // append photo count
                var date = this_gal.parent().parent().find('.date');
                date.text(date.text() + " / " + count + " Fotos");
            },
            error: function() {
                var this_gal = $('.gallery_thumbnail a[rel="' + fbid + '"]').parent();
                this_gal.removeClass("loading").addClass("ajaxerror");
            },
            timeout: 15000,
            dataType: 'xml'
        });
    });
}

function initNewsletterToggle() {
    $("a#newsletter-toggle").bind("click", function(event) {
        event.preventDefault();
        $("a#newsletter-toggle").fadeOut(100, function() {
            $("#newsletter-inputs").slideDown(300);
        });
        
        
    });
}



// ---------------------- HELPERS ------------------------- //

// helper functions for cookie handling. 
// source: http://www.quirksmode.org/js/cookies.html
function createCookie(name,value,days) {
	if (days) {
		var date = new Date();
		date.setTime(date.getTime()+(days*24*60*60*1000));
		var expires = "; expires="+date.toGMTString();
	}
	else var expires = "";
	document.cookie = name+"="+value+expires+"; path=/";
}
function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}
function eraseCookie(name) {
	createCookie(name,"",-1);
}


// preloads images 
(function($) {
  var cache = [];
  // Arguments are image paths relative to the current page.
  $.preloadImages = function() {
    var args_len = arguments.length;
    for (var i = args_len; i--;) {
      var cacheImage = document.createElement('img');
      cacheImage.src = arguments[i];
      cache.push(cacheImage);
    }
  }
})(jQuery)

// helper function for image preloading using jQuery
$.fn.image = function(src, f){
  return this.each(function(){
    $("<img>").appendTo(this).src( src ).load( f );
  });
};

// for debug
function a(where) {
  alert("here: " + where);
}


