
$(function() {

  // initialize opel player popup links
  $("a[rel=playerpopup]").click(emag.showOpelPlayerPopup).removeAttr("rel");

  // initialize image links in gallery modules
  $(".thumb a").click(emag.galleryShowImage);

  // apply link navigation for clickable teasers
  $(".clickable").click(emag.navigateClickable);

  // initialize paging
  if (emag.pagingEnabled) {
    emag.pagingInit();
  }

	// add events to dropdown navigation
	emag.dropdown();
});


var emag = new Object();
emag.pagingEnabled = true;

/**
 * show opel player popup using jquery simplemodal plugin
 */
emag.showOpelPlayerPopup = function(e) {
  e.preventDefault();
  var href = this.href;
  $.modal('<div id="popup">'
     + '<div class="head"><a href="javascript:emag.closePopup()">' + closePlayerText + ' [x]</a></div>'
     + '</div>',
     {onOpen:function (dialog) {
       dialog.overlay.show(1, function () {
         dialog.container.show(1, function () {
           dialog.data.show(1, function () {
             dialog.data.find(".head").append('<iframe src="' + href + '" class="iframe" frameborder="0" scrolling="auto" id="iframe"/>');
           });
         });
       });
     }
  });
}
emag.closePopup = function() {
  $.modal.close();
}

/**
 * show gallery image in gallery module
 */
emag.galleryShowImage = function(e) {
  e.preventDefault();
  // reset on class for all thumbnail images
  $(".thumb a").attr("class", "");
  // apply on class to current thumbnail
  $(this).attr("class", "on");

  // load href of current thumbnail in big image

  isFlash = this.href.indexOf('switchFlash_')>=0;

  mainImage = $(this).parents(".gallery").find("> .galleryMainImage")[0];
  mainFlash = $(this).parents(".gallery").find("> .galleryMainFlash")[0];
  if(!isFlash) {
    $(mainFlash).children().remove();
    $(mainImage).children().remove();
    $(mainImage).append("<img src=\""+this.href+"\" alt=\"\" width=\"235\" style=\"display:block;\">");
    $(mainFlash).hide();
    $(mainImage).show();
  } else if(isFlash) {
    $(mainFlash).children().remove();
    methodCall = this.href.substring(11); // strip 'javascript:'
    eval(methodCall+';');
    $(mainImage).hide();
    $(mainFlash).show();
  }
}

/**
 * navigate to first link found in container
 */
emag.navigateClickable = function(e) {
  e.preventDefault();
  var firstLink = $(this).find("a[href]")[0];
  if (firstLink) {
	  if(firstLink.onclick) {
		  firstLink.onclick();
	  }
	  if(firstLink.target) {
		  window.open(firstLink.href,firstLink.target).focus();
	  } else {
		  document.location = firstLink.href;
	  }
  }
}

/**
 * initialize article paging depending on page break placing
 */
emag.pagingInit = function() {

  // collect pages array, each page separated by pagebreaks
  emag.pages = new Array();
  var detectedPage = null;
  $("#main_content_area > *").each(function() {

    if ($(this).hasClass("pagebreak")) {
      detectedPage = null;
      return;
    }

    if (!detectedPage) {
      detectedPage = new Object();
      detectedPage.elements = new Array();
      emag.pages.push(detectedPage);
    }

    detectedPage.elements.push(this);

  });

  if (typeof articlePageNumber != "undefined") {
    // a sidebar article link item references a concrete page of the current article
    emag.pagingSelectPage(articlePageNumber);
  }
  else {
    // select first page
    emag.pagingSelectPage(0);
  }

}

/**
 * select page
 */
emag.pagingSelectPage = function(pPageIndex) {

  if (!(typeof pPageIndex == "number")) {
    pPageIndex = parseInt($(this).attr("rel"));
  }

  if (pPageIndex > emag.pages.length-1) {
    pPageIndex = emag.pages.length-1;
  }
  if(pPageIndex < 0) {
    pPageIndex = 0;
  }

  // select page
  emag.currentPage = emag.pages[pPageIndex];

  // toggle page visibility
  $(emag.pages).each(function() {
    if (this==emag.currentPage) {
      $(this.elements).removeClass("hideonscreen");
    }
    else {
      $(this.elements).addClass("hideonscreen");
    }
  });

  // update pagenav controls
  $("#main_content_area .pagenav").each(function() {
    // remove all if only one page
    if (emag.pages.length <= 1) {
      $(this).children().remove();
    }
    else {

      // remove sample links
      $("a[class='']", this).remove();
      $("a[class='on']", this).remove();

      // insert link for each page, highlight current page link
      var nextPage = $("a[class='next']", this);
      if (nextPage) {
        var index = 0;
        $(emag.pages).each(function() {
          var anchor = $("<a href='#' rel='" + index + "'>" + (index+1) + "</a>")
            .click(emag.pagingSelectPage);
          if (index==pPageIndex) {
            $(anchor).addClass("on");
          }
          nextPage.before(anchor);
          index++;
        });
      }

      // set reference for next page, hide on last page
      if (pPageIndex < emag.pages.length-1) {
        $(nextPage).attr("rel", pPageIndex+1).click(emag.pagingSelectPage);
        $(nextPage).show();
      }
      else {
        $(nextPage).hide();
      }

      // previous page link
      var previousPage = $("a[class='previous']", this);
      if (pPageIndex > 0) {
        $(previousPage).attr("rel", pPageIndex-1).click(emag.pagingSelectPage);
        $(previousPage).show();
      }
      else {
        $(previousPage).hide();
      }

    }
  });

}

/**
 * add mouse listener to list items on first level of main navigation
 * open/close the dropdown menu
 */
emag.dropdown =  function() {
	var closeTimeout = [];
	
	// remove formerly added classes from list item
	function removeClasses(li) {
		if (li.hasClass('last')) {
			li.removeClass('rtl');
		}
		li.removeClass('active');
	}

	$('.topnavigation > ul > li').each(function(index) {
		var index = index;

		$(this).mouseover(function() {
			window.clearTimeout(closeTimeout[index]);

			// current list item
			var li = $(this);
			
			// mark list item
			li.addClass('active');
	
			// get dropdown list
			var dropdown = li.children('ul');  
	
			// identify last list item inside current dropdown
			dropdown.children('li:last').css('border-bottom', 'none');
	
			// test, if dropdown fits into space to the right, on the last list item
			if (li.hasClass('last')) {
				// get position of list item
				function getWidth(obj) {
					return obj.get(0).clientWidth;
				}
				var space = getWidth($('.topnavigation')) - getWidth(li.parent()) + getWidth(li);
		
				// display dropdown list
				if (space < getWidth(dropdown)) {
					li.addClass('rtl');
				}
			}
		});
	});
	$('.topnavigation > ul > li').each(function(index) {
		var ix = index;

		$(this).mouseout(function() {
			var li = $(this);
	
			if ($.browser.msie && $.browser.version < 8) {
				$('.topnavigation > ul > li').each(function(index) {
					if (index != ix) {
						removeClasses($(this));
					} else {
						closeTimeout[ix] = window.setTimeout(function(){
							removeClasses(li);
						}, 100);
					}
				});
			} else {
				removeClasses(li);
			}
		});
	});
}



/** container for multiple callings of swfobject.embededSWF(...) */
var swfObjectFunctions = new Array ();