/**
 * This file contains javascript functionality for the page.
 * 
 * created: 01. Nov 2008 (DP)
 * Copyright: SF Software & Friends GmbH
 * encoding: UTF-8 [Proof: Ω]
 */

/**
 * The following is jQuery functionality that will be executed as soon as the
 * DOM is ready (roughly equal to onload).
 */
jQuery(function($) {
  // add round corners to the paragraph pictures
  roundCornersParagraphPictures();
  // add round corners on the sub-navigations
  roundCornersSubNavigation();
  // highlight search terms
  if (window.sf_search_term && (window.sf_search_term != '')) {
    highlightSearchTerm(window.sf_search_term);
  }
  // add the hover effect on the main navigation
  hoverMainNavigation();
  // add the hover effect on the banner images
  hoverBanner();
});


/**
 * Controls the hover effect on the main navigation and ensures that the
 * cursor upon the link is a pointer (Opery displays the normal one for some
 * reason).
 */
function hoverMainNavigation() {
  $("ul.main li a img").each(function() {
    $(this).hover(function() {
      // on mouse-over
      if (!this.id || (this.id == "activeMain")) {
        this.src = this.src.replace(/link/g, "hover");
      }
      this.style.cursor = "pointer"; // fix for Opera
    }, function() {
      // on mouse-out
      if (!this.id || (this.id == "activeMain")) {
        this.src = this.src.replace(/hover/g, "link");
      }
      this.style.cursor = "default"; // fix for Opera
    });
  });
}


/**
 * Controls the hover effect on the banner images and ensures that the cursor
 * upon the link is a pointer (Opery displays the normal one for some reason).
 */
function hoverBanner() {
  $(".banner img,.crossTeaser img").each(function() {
    $(this).hover(function() {
      // on mouse-over
      this.src = this.src.replace(/link/g, "hover");
      this.style.cursor = "pointer"; // fix for Opera
    }, function() {
      // on mouse-out
      this.src = this.src.replace(/hover/g, "link");
      this.style.cursor = "default"; // fix for Opera
    });
  });
}


/**
 * Adds round corners on the sub-navigations.
 */
function roundCornersSubNavigation() {
  // add the divs to all sub-navigations
  $("ul.subnav li a").wrap('<div class="subnavTL"><div class="subnavTR">'
    + '<div class="subnavBL"><div class="subnavBR"></div></div></div></div>');
  
  // change the normal sub-navigations class from normal to hover
  $("ul.subnav li.normal").each(function() {
    $(this).hover(function() {
      // on mouse-over
      $(this).removeClass("normal");
      $(this).addClass("hover");
    }, function() {
      // on mouse-out
      $(this).removeClass("hover");
      $(this).addClass("normal");
    });
  });
}


/**
 * Adds round corners on the paragraph pictures.
 */
function roundCornersParagraphPictures() {
  // adjust the image container's style
  $(".paragraph .picture").each(function() {
    var containerWidth = $(this).css("width");
    containerWidth = (parseInt(containerWidth) + 12) + "px";
    var containerLeftPos = $(this).css("left");
    if ((containerLeftPos != Number.NaN) && (containerLeftPos != 'auto')) {
      containerLeftPos = (parseInt(containerLeftPos) - 12) + "px";
      $(this).css({width: containerWidth, left: containerLeftPos});
    } else {
      $(this).css({width: containerWidth});
    }    
  });
  $(".leftColumn .picture").each(function() {
    var containerWidth = $(this).css("width");
    containerWidth = (parseInt(containerWidth) + 12) + "px";
    $(this).css({width: containerWidth});
  });
  // wrap the image in the border
  $(".picture img").wrap('<div class="rinner"></div>');
  $(".picture .rinner").before('<span class="rtop"><span class="r1"></span><span class="r2"></span>'
    + '<span class="r3"></span><span class="r4"></span></span>');
  $(".picture .rinner").after('<span class="rbottom"><span class="r4"></span><span class="r3"></span>'
    + '<span class="r2"></span><span class="r1"></span></span>');
}


/**
 * This method opens a new window and gives the window the focus. The window
 * displays no toolbar, menuebar, or location bar.
 *
 * @param argUrl The URL that should be opened in the new Window.
 * @param argTargetName The name of the new window.
 * @param argWidth The width of the new window in Pixel. Make this a number
 * without any unit. Optional, defaults to 700.
 * @param argHeight The height of the new window in Pixel. Make this a number
 * without any unit. Optional, defaults to 500.
 * @param argLeft The offset of the new window to the left screen border in
 * Pixel. Make this a number without any unit. Optional, defaults to 100.
 * @param argTop The offset of the new window to the top screen border in
 * Pixel. Make this a number without any unit. Optional, defaults to 100.
 * @param argScrollbars Defines whether the new window should display
 * scrollbars. Use either true/false or 'yes'/'no'. Optional, defaults to
 * 'yes'.
 * @param argResizeable Defines whether the new window should be resizeable.
 * Use either true/false or 'yes'/'no'. Optional, defaults to 'yes'.
 * @param argStatusbar Defines whether the new window should display the
 * status bar. Use either true/false or 'yes'/'no'. Optional, defaults to
 * 'no'.
 */
function openNewWindow(argUrl, argTargetName, argWidth, argHeight, argLeft, argTop, argScrollbars, argResizeable, argStatusbar) {
  var myTargetName  = null;
  var myScrollbars  = null;
  var myResizeable  = null;
  var myStatusbar   = null;
  var myWidth       = 0;
  var myHeight      = 0;
  var myLeft        = 0;
  var myTop         = 0;

  // init the parameters
  myTargetName = (argTargetName && (argTargetName != null)) ? argTargetName : 'newWindow';
  myWidth = (argWidth && (argWidth != null) && (argWidth != '')) ? argWidth : 700;
  myHeight = (argHeight && (argHeight != null) && (argHeight != '')) ? argHeight : 500;
  myLeft = (argLeft && (argLeft != null) && (argLeft != '')) ? argLeft : 100;
  myTop = (argTop && (argTop != null) && (argTop != '')) ? argTop : 100;
  if (argScrollbars && (typeof argScrollbars == 'boolean')) {
    myScrollbars = (argScrollbars) ? 'yes' : 'no';
  } else {
    myScrollbars = (argScrollbars && (argScrollbars != null) && (argScrollbars != '')) ? argScrollbars : 'yes';
  }
  if (argResizeable && (typeof argResizeable == 'boolean')) {
    myResizeable = (argResizeable) ? 'yes' : 'no';
  } else {
    myResizeable = (argResizeable && (argResizeable != null) && (argResizeable != '')) ? argResizeable : 'yes';
  }
  if (argStatusbar && (typeof argStatusbar == 'boolean')) {
    myStatusbar = (argStatusbar) ? 'yes' : 'no';
  } else {
    myStatusbar = (argStatusbar && (argStatusbar != null) && (argStatusbar != '')) ? argStatusbar : 'no';
  }

  // build the parameter String
  var params = 'width=' + myWidth + ',height=' + myHeight + ',left=' + myLeft + ',top=' + myTop
               + ',menubar=no,status=' + myStatusbar + ',toolbar=no'
               + ',resizable=' + myResizeable + ',scrollbars=' + myScrollbars;

  // open the window if an URL was given
  if ((argUrl != null) && (argUrl != '')) {
    myNewWindow = window.open(argUrl, myTargetName, params);
    if (myNewWindow.focus) {
      myNewWindow.focus();
    }
  }
}


/**
 * Initializes the navigation at the top. This is done when the page is first
 * loaded (to add the onclick handlers) and then whenever the displayed image
 * is changed.
 * 
 * @param currentCat The div element that represents the current category
 * (class "box_GalleryCategory"), as JQuery element. Optional, can be null.
 * @param currentThumb The link element that contains the current thumbnail
 * image (class "galleryNavPicture"), as JQuery element. Optional, can be
 * null.
 */
function initNavigation(currentCat, currentThumb) {
  // init the parameters
  if (!currentCat) {
    currentCat = $(".box_GalleryNavCategory div.current");
  }
  if (!currentThumb) {
    currentThumb = $(".navPicture a.current");
  }
  
  // change the link to the previous category
  var catPrev = currentCat.prev(".box_GalleryCategory");
  if (catPrev && catPrev[0]) {
    catPrev = catPrev.find(".navPicture a.galleryNavPicture");
    catPrev = (catPrev && catPrev[0]) ? catPrev[0] : null;
  } else {
    catPrev = null;
  }
  changeNavButton("prevCat", catPrev);
  
  // change the link to the next category
  var catNext = currentCat.next(".box_GalleryCategory");
  if (catNext && catNext[0]) {
    catNext = catNext.find(".navPicture a.galleryNavPicture");
    catNext = (catNext && catNext[0]) ? catNext[0] : null;
  } else {
    catNext = null;
  }
  changeNavButton("nextCat", catNext);
  
  // change the link to the previous image
  var imgId = currentThumb[0].id; // = thumbnailLink123
  var currentImage = imgId.substr(13);
  var imgPrev = parseInt(currentImage) - 1;
  if (imgPrev == 0) {
    imgPrev = null;
  } else {
    imgPrev = $("#thumbnailLink" + imgPrev);
    imgPrev = (imgPrev && imgPrev[0]) ? imgPrev[0] : null;
  }
  changeNavButton("prevThumb", imgPrev);
  
  // change the link to the next image
  var imgNext = parseInt(currentImage) + 1;
  imgNext = $("#thumbnailLink" + imgNext);
  imgNext = (imgNext && imgNext[0]) ? imgNext[0] : null;
  changeNavButton("nextThumb", imgNext);
}


/**
 * Changes a single navigation button according to the given parameters.
 * 
 * @param classButtonToChange The class name of the navigation button to
 * change (of the div element containing the link).
 * @param thumbLink The link element containing the thumbnail to which to link
 * the current navigation button, as HTML element.
 */
function changeNavButton(classButtonToChange, thumbLink) {
  var elemToChangeDiv = $(".box_GalleryNavJump ." + classButtonToChange);
  var elemLink = elemToChangeDiv.find("a");
  if (elemLink && elemLink[0] && thumbLink) {
    // the link element is already there
    elemLink[0].setAttribute("href", thumbLink.getAttribute("href"));
    elemLink[0].setAttribute("onclick", thumbLink.getAttribute("onclick"));
  } else if (elemLink && elemLink[0] && !thumbLink) {
    // the link element is already there, remove it
    elemLink.find("img").each(function() { this.setAttribute("src", this.getAttribute("src").replace(".gif", "_grey.gif")); }).appendTo(elemToChangeDiv);
    elemLink.remove();
  } else if (thumbLink) {
    // the link element is not there, add it
    elemToChangeDiv.wrapInner("<a></a>");
    var elemLink = elemToChangeDiv.find("a");
    elemLink[0].setAttribute("href", thumbLink.getAttribute("href"));
    elemLink[0].setAttribute("onclick", thumbLink.getAttribute("onclick"));
    elemToChangeDiv.find("img").each(function() { this.setAttribute("src", this.getAttribute("src").replace("_grey.gif", ".gif")); });
  }
}


/**
 * Changes the displayed big image, along with all navigation links and the
 * current thumbnail.
 * 
 * @param thumbnailLinkId The ID of the new current thumbnail (the thumbnail
 * that was clicked).
 * @param bigImageNew The URL of the new big image to display.
 * @param bigImageNewWidth The width of the new big image to display.
 * @param bigImageNewAlt The alt text of the new big image to display. Must be
 * safe to use in a javascript String.
 * @param bigImageNewSubline The subline of the new big image to display. Must
 * be safe to use in a javascript String.
 */
function changeImage(thumbnailLinkId, bigImageNew, bigImageNewWidth, bigImageNewAlt, bigImageNewSubline) {
  // get the thumbnail link element
  var thumbnailLink = $("#" + thumbnailLinkId);
  
  // display the new big picture
  var newBigImage = $(".box_GalleryDetailPictureBig img")[0];
  if (newBigImage) {
    newBigImage.setAttribute("src", bigImageNew);
    newBigImage.setAttribute("width", bigImageNewWidth);
    newBigImage.setAttribute("alt", bigImageNewAlt);
    newBigImage.setAttribute("title", bigImageNewAlt);
  }
  $(".galleryDetailPictureBigCaption").text(bigImageNewSubline);
  
  // remove class 'current' from the thumbnail
  $(".box_GalleryCategory a.current").removeClass("current");
  
  // add class 'current' to the thumbnail
  thumbnailLink.addClass("current");
  
  // change the thumbnail at the top
  var thumbnailTop = $(".box_GalleryNavJump .navLocation img")[0];
  var newThumbUrl = thumbnailLink.find("img")[0].getAttribute("src");
  if (thumbnailTop && newThumbUrl) {
    thumbnailTop.setAttribute("src", newThumbUrl);
  }
  
  // remove class 'current' from the category
  $(".box_GalleryNavCategory div.current").removeClass("current");
  
  // add class 'current' to the category  
  var currentCat = thumbnailLink.parents(".box_GalleryCategory").addClass("current");
  
  // change the category navigation
  initNavigation(currentCat, thumbnailLink);
  
  // return false to not follow the link
  return false;
}

       
/*****************************************************************************
        Functions for the social bookmark links
*****************************************************************************/

/**
 * Shows or hides the social bookmark layer.
 * 
 * Based on the ShareThis Wordpress plugin by Alex King.
 */
function toggleBookmarkLinks() {
  // get elements
  var layer = document.getElementById('socialBookmarkLinks');
  
  // only do this if the layer is currently hidden
  if (layer && (layer.style.display == 'none')) {
    // get the current uri and the page title
    var uri = encodeURIComponent(location.href);
    var title = encodeURIComponent(document.title);
    
    // fill in the links
        var targetUriD = initUri("http://del.icio.us/post?url={url}&amp;title={title}", uri, title);
    $("a#social_delicious").attr('href', targetUriD);
  	$("a#social_delicious").click(function() {
      return bookmarkLinkOnClick(targetUriD, 'delicious');
  	});
    var targetUriM = initUri("http://www.mister-wong.de/index.php?action=addurlamp;bm_url={url}amp;bm_description={title}", uri, title);
  	$("a#social_misterwong").attr('href', targetUriM);
  	$("a#social_misterwong").click(function() {
      return bookmarkLinkOnClick(targetUriM, 'misterWong');
  	});
    var targetUriT = initUri("http://www.technorati.com/faves?add={url}", uri, title);
  	$("a#social_technorati").attr('href', targetUriT);
  	$("a#social_technorati").click(function() {
      return bookmarkLinkOnClick(targetUriT, 'technorati');
  	});
    var targetUriB = initUri("http://blogmarks.net/my/new.php?mini=1&amp;url={url}&amp;title={title}", uri, title);
  	$("a#social_blogmarks").attr('href', targetUriB);
  	$("a#social_blogmarks").click(function() {
      return bookmarkLinkOnClick(targetUriB, 'blogmarks');
  	});
    var targetUriY = initUri("http://myweb2.search.yahoo.com/myresults/bookmarklet?u={url}&amp;t={title}", uri, title);
  	$("a#social_yahoomyweb").attr('href', targetUriY);
  	$("a#social_yahoomyweb").click(function() {
      return bookmarkLinkOnClick(targetUriY, 'yahooMyWeb');
  	});
    var targetUriG = initUri("http://www.google.com/bookmarks/mark?op=edit&amp;bkmk={url}&amp;title={title}", uri, title);
  	$("a#social_googlebookmarks").attr('href', targetUriG);
  	$("a#social_googlebookmarks").click(function() {
      return bookmarkLinkOnClick(targetUriG, 'googleBookmarks');
  	});
	}
	
  // show or hide the bookmark layer
  //$("div.socialBookmarkLinks").toggle("normal");
  if (layer && (layer.style.display == 'none')) {
    // show it
    layer.style.display = 'block';
  } else if (layer) {
    // hide it
    layer.style.display = 'none';
  }
}


/**
 * Replaces the placeholders {url} and {title} with the given URI and title.
 * 
 * @param argBaseUri The URI to initialize.
 * @param argPageUri The URI to insert for the {url} placeholder.
 * @param argPageTitle The title to insert for the {title} placeholder.
 * @return The initialized base URI.
 */
function initUri(argBaseUri, argPageUri, argPageTitle) {
	var base = argBaseUri.replace('{url}', argPageUri);
	return base.replace('{title}', argPageTitle);
}


/**
 * Executes the actions for the onclick event on the bookmark links. It opens
 * the given URI in a new window.
 * 
 * @param argUri The Uri top open.
 * @param argWindowName The name of the new window (to use as a target).
 */
function bookmarkLinkOnClick(argUri, argWindowName) {
  openNewWindow(argUri, argWindowName, 750, 500, 100, 200, true, true, true, false);
  return false;
}        
        
