/* Copyright Ideakone Oy */

Kotisivukone = {
  popup: function(url, width, height) {
    var win = window.open(url, name, "toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=" + width + ", height=" + height)
    win.focus();
    return false;
  }
}

function init() {
  // Edit mode
  if (window.initEdit != null) {
    initEdit();
    Initialize.checkContentWidth("content_view"); // FIXME also frontpage's blog etc
  }
  else Initialize.checkContentWidth("content");

  if (window.stateFunction != null) stateFunction();
  // Clients script
  if (window.pageInit != null) pageInit();
}


Initialize = {
  // Scale some content
  checkContentWidth: function(elem) {
    if (document.getElementById && document.getElementById(elem)) {
      var element = document.getElementById(elem);
      var orig = element.innerHTML;

      if (window.disableWidthCheckIfScripts != null &&
          window.disableWidthCheckIfScripts != undefined &&
          window.disableWidthCheckIfScripts == true &&
          orig.indexOf("script") != -1) return;

      if (window.disableWidthCheck != null &&
          window.disableWidthCheck != undefined &&
          window.disableWidthCheck == true) return;

      // Padding, etc.
      var decreaseWidthBy = 40;

      if (window.decreaseWidthBy != null &&
          window.decreaseWidthBy != undefined &&
          window.decreaseWidthBy > 0)
          decreaseWidthBy = window.decreaseWidthBy;

      // Get max width for IE7&FF and IE6 etc
      var maxWidth = 0;
      // IE 7, mozilla, safari, opera 9
      if (window.XMLHttpRequest) {
        maxWidth = element.offsetWidth;
      }
      // IE6, older browsers
      else {
        element.innerHTML = "";
        var maxWidth = element.offsetWidth;
        element.innerHTML = orig;
      }
      // maxWidth is the absolute width of the element
      // elements inner width can be smaller (padding etc.)
      //maxWidth -= decreaseWidthBy;

      // Scale
      if (maxWidth > 100) {
        var elems = document.getElementById(elem).getElementsByTagName("img");
        for (var i=0; i<elems.length; i++)
          if (elems[i].offsetWidth > maxWidth)
            elems[i].style.width = (maxWidth - decreaseWidthBy) + "px";
        elems = document.getElementById(elem).getElementsByTagName("table");
        for (var i=0; i<elems.length; i++)
          if (elems[i].offsetWidth > maxWidth)
            elems[i].style.width = (maxWidth - decreaseWidthBy) + "px";
      }
    }
  }

}

menu = function() {
  if (document.getElementById && document.getElementById("navi")) {
    var items = document.getElementById("navi").getElementsByTagName("LI");
    for (var i=0; i<items.length; i++) {
      items[i].onmouseover = function() { this.className += " hover";  }
      items[i].onmouseout = function() { this.className = this.className.replace(new RegExp(" hover\\b"), ""); }
    }
  }
}
if (window.attachEvent) window.attachEvent("onload", menu);

// For sport clubs
function swapImage(id, src) {
  if (document.getElementById && document.getElementById(id)) {
    document.getElementById(id).src = src;
  }
}
function popUpImage(id, width, height) {
  if (document.getElementById && document.getElementById(id)) {
    var win = window.open(document.getElementById(id).src, "image","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=" + width + ", height=" + height)
    win.focus();
    return false;
  }
}
function popup(url) {
  var win = window.open(url, "kotisivukone_popup","toolbar=no, location=no, directories=no, status=no, menubar=no, scrollbars=yes, resizable=yes, copyhistory=no, width=250, height=300")
  win.focus();
  return false;
}

/* Changes date on calendar */
function changeCalendarDate(pageid, hash, action, year, month, page_root_url, boxID, subset) {
  new Ajax.Updater(boxID, page_root_url + '?ajax',
    {parameters:'resource=calendar_block_change_date&action=' + action + '&year=' + year + '&month=' + month +
                '&subset=' + subset + '&pageid=' + pageid + '&hash=' + hash + '&page_root_url=' + page_root_url,
     asynchronous:true, evalScripts:true
  });
}


/* Refreshes position of topbar logo */
function positionLogo ()
{
       var tbx = findPosX(document.getElementById('top-bar'));
       var tby = findPosY(document.getElementById('top-bar'));

    $("logo").style.left = (logo_position_x + tbx) +'px';
    $("logo").style.top =  (logo_position_y + tby) +'px';

    $("logo_text").style.left = (logo_text_position_x + tbx) +'px';
    $("logo_text").style.top =  (logo_text_position_y + tby) +'px';
}

function findPosX(obj) {
  var curleft = 0;
  if(obj.offsetParent)
    while(1) {
      curleft += obj.offsetLeft;
      if(!obj.offsetParent)
        break;
        obj = obj.offsetParent;
      }
  else if(obj.x)
    curleft += obj.x;
  return curleft;
}

function findPosY(obj) {
  var curtop = 0;
  if(obj.offsetParent)
    while(1) {
      curtop += obj.offsetTop;
      if(!obj.offsetParent)
        break;
        obj = obj.offsetParent;
      }
  else if(obj.y)
    curtop += obj.y;
  return curtop;
}

function go(url) { window.location = url; }


// Album height adjusting to square, no css way possible?
function albumModernImproveBoxHeight(div) {
  $(div).select('.album_image_modern_borders').each(function(el) {
    el.style.height = el.offsetWidth + 'px';
    el.select('img').each(function(el) {el.style.maxHeight = '89%';}); // Needed for  chrome weirdly??? Fixme?
    if (el.up().className.indexOf('album_modern_right_bar_sizer') == -1) {
      el.up().style.height = el.offsetWidth + 35 + 'px';
    }
  });
}

function URLDecode(s) {
  var lsRegExp = /\+/g;
  return unescape(String(s).replace(lsRegExp, " "));
}

shareData = {
	prepareImage:function(pageId, pageIdHash, hoderId, isMadpage, type){
		var image;
		if(isMadpage != null && typeof(isMadpage) != 'undefined' && isMadpage){
			image = $('madpages_content').select('.madpages_component img.madpages_image ').first();
		}else{
			image = $('content').select('.content_table img').first();
		}
		
		if(image != null){
			var src = image.src;
			if(isMadpage != null && typeof(isMadpage) != 'undefined' && isMadpage){
				src = image.getAttribute('data-src-orig');
			}
			src = src.substring(src.indexOf('/files'), src.length);
		 	thumbUrl = src;
		 	
		 	var replaceable = thumbUrl.substring(thumbUrl.lastIndexOf('.'));
		 	thumbUrl = thumbUrl.replace(replaceable, '_50x50' + replaceable);
			replaceable = thumbUrl.substring(0, thumbUrl.lastIndexOf('/'));
			thumbUrl = thumbUrl.replace(replaceable, replaceable + '/.thumbs');
			var imageSrc = '/Kotisivukone/app/thumbnail?waitfor=false&height=50&width=50&img=' + src + '&hash=' + pageIdHash + '&id=' + pageId;
			var image = new Element('img');
			$(hoderId).insert(image);
			image.src = imageSrc;
			
			
		}else{
			switch (type){
				case 'blog' : 
					thumbUrl = root_img+'www/pics/social_network/icon_blog.png';
					break;
				case 'news' :
					thumbUrl = root_img+'www/pics/social_network/icon_news.png';
					break;
				case 'madpages' :
					thumbUrl = root_img+'www/pics/social_network/icon_sites.png';
					break;
				case 'page' :
					thumbUrl = root_img+'www/pics/social_network/icon_sites.png';
					break;
				default: 
					thumbUrl = '';
					break;
			}
		}
		this.initImage(thumbUrl);
	},
	initUrl:function(url){
		if($('url_meta') != null){
			$('url_meta').content = url;
		}else{
			document.getElementsByTagName('head').item(0).appendChild(new Element('meta', {property: 'og:url', id: 'url_meta', content:url}));
		}
    	$$('a[class^=addthis_button]' ).each(function(el){
    		el.setAttribute("addthis:url",url);
    	});
	},
	initImage:function(image){
		
		if($('facebook_image') != null){
			$('facebook_image').href = image;
		}else{
			document.getElementsByTagName('head').item(0).appendChild(new Element('link', {rel:'image_src', id: 'facebook_image', href:image}));
		}
		if($('image_meta') != null){
			$('image_meta').content = image;
		}else{
			document.getElementsByTagName('head').item(0).appendChild(new Element('meta', {property: 'og:image', id: 'image_meta', content:image}));
		}

	}
}
