/************************************
 * MUISTA PAIVITTAA YLE_PACK.JS !!!
 ************************************/

/* Fix activex component initialization for IE */
function activeXfix() {
    var ua = navigator.userAgent;

    if (ua.indexOf('MSIE') > -1 && ua.indexOf('Opera') == -1) {
	    var objects = document.getElementsByTagName('object');

		for (var i=0; i < objects.length; i++) {
			var html = objects[i].outerHTML;
			
			if(html.indexOf(".swf\"") == -1)
				objects[i].outerHTML = html;
    	}
    }
}


/*
 * create new windows from css-class.
 * Examples of usage:
 * <a href="/foobar.html" class="new-window">Open new win!</a> <!-- new window -->
 * <a href="/foobar.html" class="new-window width-500 height-700">Pop me!</a> <!-- popup with dimensions defined -->
 * <a href="/foobar.html" class="new-window width-500 height-700 scrollbars">Pop me with scrollbars!</a> <!-- popup with dimensions defined and forced scrollbars -->
 */

// Create the new window
function openInNewWindow() {
  var width = -1;
  var height = -1;
  var scrollbars = 'auto';
  if (!!this.className) {
    var index = this.className.search('width-');
    if (index != -1) width = parseInt(this.className.substring(index + "width-".length, index + "width-".length+3));
    index = this.className.search('height-');
    if (index != -1) height = parseInt(this.className.substring(index + "height-".length, index + "height-".length+3));
    if (this.className.search('scrollbars') != -1) scrollbars = '1';
  }

  var params = (width<0 && height<0)? 'status=1,toolbar=1,location=1,directories=1,menubar=1,resizable=1,scrollbars='+scrollbars : 'scrollbars='+scrollbars+',width='+width+',height='+height;
  var newWindow = window.open(this.getAttribute('href'), '_blank', params);
  if (newWindow) {
    newWindow.focus();
    return false;
  }
  return true; //Use href as "normal" link
}

// Add the openInNewWindow function to the onclick event of links with a class name of "new-window"
function getNewWindowLinks() {
	// Check that the browser is DOM compliant
	if (document.getElementById && document.createElement && document.appendChild) {
		// Change this to the text you want to use to alert the user that a new window will be opened
		var strNewWindowAlert = " ";
		// Find all links
		var links = document.getElementsByTagName('a');
		for (var i = 0, link, strWarningText, objWarningText; link = links[i]; i++) {
			// Find all links with a class name of "new-window"
			if (/\bnew\-window\b/.exec(link.className)) {
				// Create an em element containing the new window warning text and insert it after the link text
				objWarningText = document.createElement("em");
				strWarningText = document.createTextNode(strNewWindowAlert);
				objWarningText.appendChild(strWarningText);
				link.appendChild(objWarningText);
				link.onclick = openInNewWindow;
			}
		}
		objWarningText = null;
	}
}

/* pullquote function by Roger Johansson, http://www.456bereastreet.com/ */
var pullquote = {
	init : function() {
	// Check that the browser supports the methods used
		if (!document.getElementById || !document.createElement || !document.appendChild) return false;
		var oElement, oPullquote, oPullquoteP, oQuoteContent, i, j;
	// Find all span elements with a class name of pullquote
		var arrElements = document.getElementsByTagName('span');
		var oRegExp = new RegExp("(^|\\s)pullquote(\\s|$)");
		for (i=0, oElement; oElement = arrElements[i]; i++) {
	// Save the current element
			if (oRegExp.test(oElement.className)) {
	// Create the blockquote and p elements
				oPullquote = document.createElement('blockquote');
				oPullquote.className = oElement.className
				oPullquoteP = document.createElement('p');
	// Insert the pullquote text
				for(j=0;j<oElement.childNodes.length;j++) {
					oPullquoteP.appendChild(oElement.childNodes[j].cloneNode(true));
				}
				oPullquote.appendChild(oPullquoteP);
	// Insert the blockquote element before the span elements parent element
				oElement.parentNode.parentNode.insertBefore(oPullquote,oElement.parentNode);
			}
		}
	},
	// addEvent function from http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
	addEvent : function(obj, type, fn) {
		if (obj.addEventListener)
			obj.addEventListener( type, fn, false );
		else if (obj.attachEvent)
		{
			obj["e"+type+fn] = fn;
			obj[type+fn] = function() { obj["e"+type+fn]( window.event ); }
			obj.attachEvent( "on"+type, obj[type+fn] );
		}
	}
};

/* Adds even and odd classes to table rows or cells. Stripe tables with css-class stripe */
ELEMENT_NODE = 1;
	
function stripedTables() {
  stripeTables('stripe');
}

function stripeOneTable(table, evenClassName, oddClassName)
{
	var rows = table.getElementsByTagName('tr');

	for (var i=0, row; row = rows[i]; i++) {
		var index = 0;
		
		row.className += ' ' + ((i % 2 == 0) ? evenClassName : oddClassName);
		
		for (var j=0; j < row.childNodes.length; j++) {
			var node = row.childNodes[j];
			
			if (node.nodeType != ELEMENT_NODE)
				continue;
				
			if (node.tagName.toLowerCase() == 'td' || node.tagName.toLowerCase() == 'th') {
				node.className += ' ' + ((index % 2 == 0) ? evenClassName : oddClassName);
				index++;
			}
		}

	}
}

function stripeTables(className) 
{
	var tables = document.getElementsByTagName('table');
	
	for (var i = 0, table; table = tables[i]; i++) {
		if (table.className.indexOf(className) > -1)
			stripeOneTable(table, 'even', 'odd');
	}
}

/**
 * This function might be useful for image gallery pages.
 * Add attribute class="thumbnail" and the script will take care of rest.
 */
function displayImgOnClick(e) {
  if (!e) var e = window.event;
  var container_name = 'automaticThumbnailContainerElement';
  var posx = 0;
  var posy = 0;
  var img_path = this.getAttribute('href');
  var title = this.getAttribute('title');

  if (!e) var e = window.event;
  if (e.pageX || e.pageY) {
    posx = e.pageX;
    posy = e.pageY;
  }
  else if (e.clientX || e.clientY) {
    //posx = e.clientX + document.body.scrollLeft;
    //posy = e.clientY + document.body.scrollTop;
    var de = document.documentElement;
    var b = document.body;
    posx = e.clientX + (de.scrollLeft || b.scrollLeft) - (de.clientLeft || 0);
    posy = e.clientY + (de.scrollTop || b.scrollTop) - (de.clientTop || 0);
  }

  var container = document.getElementById(container_name);
  if (container) {
    clearElem(container);
  }
  else {
    container = document.createElement('div');
    container.setAttribute('id', container_name);
  }
  
  var closebtn = document.createElement('a');
  closebtn.href = '#';
  closebtn.onclick = function () { document.getElementById(container_name).style.display='none'; return false; }

  posy = (posy - 200) + 'px';
  posx = (posx - 200) + 'px';
  //var styles = "border:1px solid #000; z-index:2; display:block; position:absolute; top:"+posy+"; left:"+posx;
  //container.setAttribute("style", styles);
  //IE needs these notations
  container.style.backgroundColor = '#fff';
  container.style.padding = '10px';
  container.style.position = 'absolute';
  container.style.top = posy;
  container.style.left = posx;
  container.style.zIndex = 2;
  container.style.display = 'block';

  var img = document.createElement("img");
  img.setAttribute("src", img_path);
  img.setAttribute("alt", "");
  //img.setAttribute("style", "display:block;");
  img.style.display = 'block';

  closebtn.appendChild(img);
  container.appendChild(closebtn);

  if (title && title != '') {
    var p = document.createElement("p");
    p.style.padding = '0';
    p.style.margin = '2px';
    p.style.textAlign = 'center';
    p.appendChild(document.createTextNode(title));
    container.appendChild(p);
  }
  document.body.appendChild(container);

  return false;
}

/**
 * Remove every childNode the given element has.
 */
function clearElem(containerNode) {
  if (!containerNode) return false;
  while (containerNode.hasChildNodes())
    containerNode.removeChild(containerNode.lastChild);
}

function checkThumbnails() {
  var links = document.getElementsByTagName('a');
  for (var i = 0, link; link = links[i]; i++) {
    // Find all links with a class name of "thumbnail"
    if (/\bthumbnail\b/.exec(link.className)) {
      link.onclick = displayImgOnClick;
    }
  }
}

/**
 * Load new uri to browser window.
 * @param  newLocation String Absolute or relative path works in most modern browsers
 * @return boolean False if given newLocation is empty, -1 or # character. Otherwise true is returned.
 * Example of usage in HTML code:
 * <!-- This link will eventually load desired uri even if javascript is disabled: -->
 * <a href="http://yle.fi/" onclick="return function() {  doSomethingFancyFirst(); return !gotoUri('http://yle.fi/');  }"> yle.fi </a>
 */
function gotoUri(newLocation) {
  if (!newLocation || newLocation=='' || newLocation=='-1' || newLocation=='#') return false;
  window.location = newLocation;
  return true;
}

/**
 * Normalize heights of elements in a "row"
 * Search for class="equalize-items-every-N" where N is positive integer
 * TODO: doesn't work well with values other than 3..
 * Example of usage in HTML code:
 * <ul class="normalize-items-every-3"> ...
 */
function normalizeLists() {
  var keyword = 'normalize-items-every-'; //The classname to look for
  
  //Concatenate all the unordered and ordered lists
  var lists = mergeArrays(document.getElementsByTagName('ul'), document.getElementsByTagName('ol'));
  
  for (var i=0; i<lists.length; i++) { //Loop thru all list elements
    if (!lists[i].className) continue;
    var index = lists[i].className.search(keyword);

    //Bingo! Desired classname found.
    if (index != -1) {
      //equalize-items-every-2, equalize-items-every-3, equalize-items-every-4 and so on...
      var itemsPerRow =  parseInt(lists[i].className.substring(index+keyword.length, index+keyword.length+1));

      var items = lists[i].getElementsByTagName('li');
      var maxHeightInRow = 0;

      for (var j=0; j<items.length; j++) {
        var height = items[j].offsetHeight;
        if (height > maxHeightInRow) maxHeightInRow = height;

        if (j%itemsPerRow==itemsPerRow-1 || j==items.length-1) {
          for (var k=0; k<itemsPerRow; k++) {
            //Update each element in the row:
            //Set the height css property to 20 pixels over the maximum offsetHeight of the tallest element in the row
            items[j-k].style.height = (maxHeightInRow+20)+'px';
          }
        }
        else if (j%itemsPerRow == 0) {
          items[j].className = (!!items[j].className)? items[j].className+' first-in-row' : ' first-in-row';
          maxHeightInRow = 0;
        }
      }

    }
  }
}

/**
 * Merge two or more arrays into a single array.
 * Example of usage:
 * var mergedArr = mergeArrays (myArr, myOtherArr, myThirdArr);
 */
function mergeArrays() {
  if (!arguments.length) return null;
  var combinedArray = arguments[0];
  for (var i = 0; i < arguments.length; i++) {
    var arr = arguments[i];
    for (var j = 0; j < arr.length; j++) combinedArray[combinedArray.length] = arr[j];
  }
  return combinedArray;
}

/**
 * Add automatic page loading functionality to select elements (pulldowns).
 * Each option element should have desired link url inside value attribute
 * Example of usage in HTML code:
 * <select class="autolink">
 *   <option value="http://www.yle.fi/tv1/">TV1</option>
 *   <option value="http://www.yle.fi/tv2/">TV2</option>
 *    ...
 */
function autoSelectLinks() {
  if (!document.getElementsByTagName) return;
  var selects = document.getElementsByTagName("select");
  if (!selects) return;
  for (var i=0, select; select = selects[i]; i++) {
    if (select.className.search("autolink") != -1) {
       select.onchange = function() { gotoUri(this.options[this.selectedIndex].value); };
    }
  }
}

/**
 * Perform various styling operations to img elements on the page, such as detecting align attributes (created by some wysiwyg editors).
 */
function formatImageElements() {
  var images = document.getElementsByTagName('img');
  for (var i=0, image; image = images[i]; i++) {
    // Find all images with 'align' attribute
    if (image.align) {
      var aligned_to = 'on-' + image.align;
      image.className = image.className + ' ' +aligned_to;
    }
  }
}

function ylefi_header_init() {
  ylefi_header_customize();
}

function ylefi_header_customize() {
  var $global_header = $("#global-header");
  // hide shortcut submit button
  $("#content-shortcuts button", $global_header).hide();
  // clear serch field
  $("form.ylefi-search label input", $global_header).click(function(){$(this).css({'background-image': 'none'})});
}

// function for initializing ylefi bubbles
function ylefi_bubble_init() {
  ylefi_bubble_add_events();
}

// function for setting events
function ylefi_bubble_add_events() {
  var debug = "";//typeof jQuery.fn.hoverIntent;
  $("body").append("<div id=\"ylefi-bubble\" class=\"hide "+debug+"\"></div>");
  $("#ylefi-bubble").hide();
  
  if (typeof jQuery.fn.hoverIntent == 'undefined') {
    $("#ylefi-bubble").hover(function(){$("#ylefi-bubble").show();}, function (){$("#ylefi-bubble").hide();});
  }
  else {
    $("#ylefi-bubble").hoverIntent(function(){$("#ylefi-bubble").show();}, function (){$("#ylefi-bubble").hide();});
  }
  $("ul.ylefi-bubble a > img").hover(ylefi_bubble_control_desc, ylefi_bubble_control_desc); 
}

// function for controlling bubbles
function ylefi_bubble_control_desc(e) {
  var $ylefi_bubble = $("#ylefi-bubble");
  if($(this).attr("alt")){
    e = e || window.event;
    //alert($(this).attr("alt"));
    $("#ylefi-bubble").html("<p>"+$(this).attr("alt")+"</p>");
    var offset = $(this).offset();
    /*
    if (e.type == 'mouseover') {
      $ylefi_bubble.fadeIn('fast');
      $ylefi_bubble.css({
        left: (offset.left + (70)) + 'px',
        top: (offset.top - (65)) + 'px'
      });
    } else if (e.type == 'mouseout') {
      $ylefi_bubble.hide();
    }
    */
    // fix for jquery 1.1.2 mouseover = mouseenter, mouseout = mouseleave
    if (e.type == 'mouseenter') {
      $ylefi_bubble.fadeIn('fast');
      $ylefi_bubble.css({
        left: (offset.left + (70)) + 'px',
        top: (offset.top - (65)) + 'px'
      });
    } else if (e.type == 'mouseleave') {
      $ylefi_bubble.hide();
    } else if (e.type == 'mouseover') {
      $ylefi_bubble.fadeIn('fast');
      $ylefi_bubble.css({
        left: (offset.left + (70)) + 'px',
        top: (offset.top - (65)) + 'px'
      });
    } else if (e.type == 'mouseout') {
      $ylefi_bubble.hide();
    } 
  }
}

executeWhenJQueryReady(function() {
  ylefi_header_init();
  YLE.loadingReady();
  if ($("#global-footer").length == 0) return; //Vanhat saitit
  if (YLE.loadingTime() < 10 && navigator.userAgent.indexOf('iPhone') == -1) {
    if ($("#ylefi-stripe").length == 0 && $("#global-footer.no-ylefi-stripe").length == 0) {
      $.getScript("http://static.yle.fi/global/api/js/?service=ylefi_stripe");
    }
  }
  $.getScript("http://www.yle.fi/global/api/js/?service=ylefi_account"); //Use www.yle.fi instead of static.yle.fi to avoid caching
});


//addLoadEventHandlers(activeXfix, getNewWindowLinks, stripedTables, pullquote.init, checkThumbnails);
//activeXFix caused problems with embedded wmv object => IE will report about "unsafe manner of using ActiveX script"
addLoadEventHandlers(getNewWindowLinks, stripedTables, pullquote.init, checkThumbnails, autoSelectLinks, normalizeLists, formatImageElements);
