// this is needed for functionality of some drupal components, so take the control back
$ = jQuery.noConflict();

Suomi24 = {};

// detect mobile browser and direct to m.suomi24.fi
function isMobileBrowser(){
  var a=["iphone","ipod","series60","symbian","android","windows ce","palm","blackberry","samsung","opera mini","webos","windows phone","nokia","sonyericsson","htc","brew"];
  var d=navigator.userAgent.toString().toLowerCase();
  for(var c=0; c<a.length; c++){
    var b=d.indexOf(a[c]);
    if(b&&b>-1){
      return true;
    }
  }
  return screen.width<801;
}

if((window.location.hostname.indexOf("keskustelu") > -1 || ( window.location.hostname.indexOf("www") > -1 && window.location.pathname == "/" ))  && top === self ){ // check for mobile browser if in keskustelu or www, and not inside iframe
  var mobileBrowser = isMobileBrowser();
}

if(typeof(mobileBrowser) != "undefined" && mobileBrowser == 1){
  // if coming to page with hash #nomob, means that we came from mobile and want to stay in the full version
  if(window.location.hash == "#nomob"){
    $.cookie("mobileRedir", 0, {domain: "suomi24.fi", expires: 14});
  }
  
  var mobile = 0; // whether to use mobile version
  if($.cookie("mobileRedir") == null){
    if(confirm(Drupal.t("Käytät ilmeisesti mobiililaitetta. Haluatko siirtyä matkapuhelimelle optimoituun versioon?"))){
      mobile = 1;
    }
  }else{
    mobile = $.cookie("mobileRedir");
  }
  $.cookie("mobileRedir", mobile, {domain: "suomi24.fi", expires: 14});
  
  if(mobile == 1){
    // if in keskustelu, redirect to the corresponding page, otherwise to frontpage
    if(window.location.hostname.indexOf("keskustelu") > -1){
      window.location = "http://m.suomi24.fi"+window.location.pathname;
    }else{
      window.location = "http://m.suomi24.fi";
    }
  }
}

var animSpeed = 500; // default animation speed for effects (ms). This is modified depending on action (e.g. animSpeed/2)

var d = new Date();
var h = d.getHours();
var m = d.getMinutes();
var s = d.getSeconds();
var ms = d.getMilliseconds();
var timeformatted = h.toString() + m.toString() + s.toString() + ms.toString();

var emediatetime = Math.round(new Date().getTime() / 1000);

var ie=false;  // ie?
var ie7=false; // ie7 or older ?
var ie8=false; // ie7 or older ?
var ie9=false;
if(jQuery.browser.msie){
	ie=true;
	if(parseInt(jQuery.browser.version) < 8) {
		ie7 = true;
	}
	else if(parseInt(jQuery.browser.version) == 8) {
		ie8 = true;
	}
	else if(parseInt(jQuery.browser.version) > 8) {
		ie9 = true;
	}
}

// detect touchscreen
if ("ontouchstart" in document.documentElement){
	jQuery(document).addClass("touch");
}

Suomi24.strings = {
	// an anonymous user has changed settings and cookie is written
	settingsChangedAlert: Drupal.t('<p>Olet muokannut etusivua ja muutokset on tallennettu väliaikaisesti. Kirjautumalla sisään voit tallentaa muutokset pysyvästi.</p><a href="http://oma.suomi24.fi/user/register?wanted_url=http%3A%2F%2Fwww.suomi24.fi" class="S24_more">Kirjaudu sisään tai liity jäseneksi</a>'),
	ajaxContentNotFound: Drupal.t('Sisältöä ei löytynyt')
};


// SITE FUNCTIONALITY IN ALPHABETICAL ORDER
Suomi24.ads = {
  entrance: {
    hideTimerId: 0,
    init: function(){
      this.entranceElem = $("#S24_entrance");
      if($("#S24_entrance .S24_banner > *").not("script, noscript").length > 0){ // if ad content available
        document.body.className += " hasEntrance";
        entranceContent = jQuery('<div id="S24_entranceContent"><div class="S24_logo S24_fl"><img src="http://suomi24-static.fi/b/img/suomi24.png" alt="" /></div></div>').click(function(){Suomi24.ads.entrance.hide()});
        entranceLifts = jQuery('<div id="S24_entranceLifts">').appendTo(entranceContent).load("/static/elements/stripe/keskustelu.html", function(){
          entranceLifts.find("img").remove();
          entranceLifts.find("#S24_hotTopics").attr("id", "S24_entranceTopics");
          entranceLifts.find("ul").addClass("S24_linklist").css({clear: "both"});
          if($("body").hasClass("S24_frontpage")){
            entranceLifts.find("a").each(function(i, elem){ 
              $(elem).attr("href","#");
              $(elem).click(function(){
                window.location.href=$($("#S24_maincol .S24_page_header").get(i)).find("h2 > a").attr("href"); 
                return false;
              });
            });
          }
        });
        jQuery("#S24_entrance").before('<a href="#" onclick="Suomi24.ads.entrance.hide(); return false;" id="S24_entranceHide" class="S24_continue">'+Drupal.t("Jatka sivustolle")+'</a>').append(entranceContent);
        this.startHideTimer();
      }
    },
    startHideTimer: function (){
      this.hideTimerId = setTimeout (function(){Suomi24.ads.entrance.hide();}, 15000);
    },
    hide: function() {
      this.entranceElem.hide();
      $("body").removeClass("hasEntrance");
      clearTimeout(Suomi24.ads.entrance.hideTimerId);
    }
  },

  interstitial: {
    hideTimerId: 0,
    init: function() {
      if(jQuery("#interstitialWrapper").length > 0 ){
        jQuery("#interstitialContent").prepend('<a href="#" onclick="Suomi24.ads.interstitial.hide(); return false;" id="interstitialHide">Sulje mainos</a>');
        this.startHideTimer();
        this.show();
      }
    },
    show: function() {
      jQuery("#interstitialWrapper").show();
      jQuery("body").addClass("hasInterstitial");
    },
    startHideTimer: function (){
      this.hideTimerId = setTimeout (function(){Suomi24.ads.interstitial.hide();}, 10000);
    },
    hide: function() {
      jQuery("#interstitialWrapper").hide();
      jQuery("body").removeClass("hasInterstitial");
      clearTimeout(Suomi24.ads.interstitial.hideTimerId);
    }
  },
  
  corner: function(){
    var $corner = $("#S24_corner");
    if($("#S24_corner .S24_banner > *").not("script").length > 0){ // if ad content available
      var $close = $corner.prepend("<a id='S24_cornerClose'>"+Drupal.t("Sulje")+"</a>");
      $close.click(function(){
        $corner.hide();
      });      
    }
  }
};

if(typeof activeBubbles == "undefined"){
	var activeBubbles = Array();
}
Suomi24.ajaxBubble = {
  
  init : function() {
	 links = jQuery("a.S24_ajax-bubble");
	 if(links.length > 0){
		this.bindEvents(links);
	 } else {
		return;
	 }
  },
  bindEvents: function(o) {		
	  o.live("click", function(e) {
			e.preventDefault();
			 
			var bubble = addBubble(jQuery(this));
			e.stopPropagation();
			
			// remove bubble when clicking outside
			
			// IE is bad on old jQuery version
			var outsideClickEl = jQuery(document);
			if(ie && jQuery().jquery == "1.3.2"){
				outsideClickEl = jQuery("body");
			}
			
			outsideClickEl.click(function(ev){ // document works for good browsers and new version of 
				// only close if clicked with left button or by jquery click trigger (also to prevent firefox bug)
				if((!(ev.which != 1) || typeof(ev.which) == "undefined") && !jQuery(ev.target).hasClass("S24_ajax-bubble") && !jQuery(ev.target).parents().hasClass("S24_ajax-bubble")){
					if(bubble.hasClass("removable")){
						bubble.remove();
					}else{
						bubble.hide();
					}
				}
			});	
			bubble.click(function(ev){
				ev.stopPropagation();
			});
	  });
		
	  function addBubble(o, cache) {
			if(typeof(cache) == "undefined"){
				cache="true";
			}
			
			// if the bubble already exists
			if(typeof(o.attr("data-bubbleId")) != "undefined" && jQuery("#"+o.attr("data-bubbleId")).length > 0){
				
				Suomi24.ajaxBubble.clearBubbles();
				var addedBubble = jQuery("#"+o.attr("data-bubbleId"));
				if(addedBubble.length > 0){
					Suomi24.ajaxBubble.positionBubble(o, addedBubble);
					addedBubble.show();
				}
			}else{	
				var addedBubble;
				Suomi24.ajaxBubble.clearBubbles();		
				var randomID = "bubble-"+Math.floor(Math.random()*1000000);
				o.attr("data-bubbleId", randomID);
				activeBubbles.push("#"+randomID);
				var pathModifier = ""; //where the ajax files are
			
				var contUrl = pathModifier + o.attr("data-href");
				 
				// remove existing bubbles and other similar content
				//Suomi24.ajaxBubble.clearBubbles();
				jQuery("#S24_update_status-bubble").hide();
				
				// check if same url has already been loaded to prevent ununique IDs: go through the active bubbles
				var makeNew = true;
				var activeNum = activeBubbles.length;
				for(var i = 0; i<activeNum; i++){
					var cBubble = $(activeBubbles[i]);
					if(cBubble.attr("data-url") == contUrl){ // same url found
						makeNew = false;
						addedBubble = cBubble;
					}
				}
				
				if(makeNew){
					code = "<div class='S24_ajax-bubble-container' id='"+randomID+"' data-url='"+contUrl+"'><div class='S24_ajax-bubble-topRightBrd'></div><div class='S24_ajax-bubble-topLeftBrd'></div><div class='S24_ajax-bubble-contentWrapOut'><div class='S24_ajax-bubble-contentWrap'><div class='S24_ajax-bubble-content'></div></div></div><div class='S24_ajax-bubble-bottomRightBrd'></div><div class='S24_ajax-bubble-bottomLeftBrd'></div><div class='S24_ajax-bubble-arrow'></div></div>";
					addedBubble = jQuery(code).appendTo(jQuery("body")).hide();
				}
				
				Suomi24.ajaxBubble.positionBubble(o, addedBubble);
				
				if(makeNew){
					// loading animation
					var bubbleContent = addedBubble.find(".S24_ajax-bubble-content").addClass("loading");
					request = jQuery.ajax({
						type: "GET", 
						url: contUrl,
						async: true,
						dataType: "html",
						error: function() {
							bubbleContent.removeClass("loading").html(Suomi24.strings.ajaxContentNotFound);
						},
						success: function(data) {
							if(data != "") {
								bubbleContent.removeClass("loading").empty().append(data);
							} else {
								bubbleContent.removeClass("loading").empty().append(Suomi24.strings.ajaxContentNotFound);
							}
														
							bubbleContent.find(".S24_close, .S24_cancel").not(".S24_ajaxBubble-noclose").click(function(){
								if(addedBubble.hasClass("removable")){
									addedBubble.remove();
								}else{
									addedBubble.hide();
								}
							});
						}
					});	
				}
			}
			
			addedBubble.show();
			return addedBubble;
	  }
  },
	clearBubbles: function(){
		if(activeBubbles.length>0){
			var selector = activeBubbles.join(",");
			var targets = jQuery(selector);
			targets.filter(".removable").remove();
			jQuery(selector).hide();
		}
	},
	positionBubble: function(o, bubble){
		var linkOffset = o.offset();
						
		var leftSide = false;
		// if parent is in the right side of page, bubble should go to the left
		if(linkOffset.left > jQuery(window).width()/2){
			leftSide = true;
		}
						
		if(leftSide) {
			// position bubble to the left
			var position = jQuery(window).width()-(linkOffset.left + parseInt(o.css("margin-left")));
			bubble.addClass("S24_ajax-bubble-left").css("right", position).css("top", linkOffset.top + o.height()/2);
		} else {
			// to the right
			var position = linkOffset.left + parseInt(o.css("margin-left")) + (o.width()+parseInt(o.css("padding-right")) + parseInt(o.css("padding-left")));
			bubble.addClass("S24_ajax-bubble-right").css("left", position).css("top", linkOffset.top + o.height()/2);
		}
		if(ie7){
			bubble.css("width", bubble.width()+"px");
		}
	}
};

var highlightedComment = jQuery("");
Suomi24.comments = {
	highlightHashComment: function(){ // Highlight comment on nodepage if url hash used
		highlightedComment.removeClass("highlighted");
		
		if(window.location.hash != "") {
			window.location = window.location.hash.replace("-view", "");
		}
		
		var marked = "#"+escape(window.location.hash.substring(1)); 
		if(marked.length > 1){
		 highlightedComment = jQuery(marked);
		 highlightedComment.removeClass("collapsed").addClass("highlighted");
		}
	},

	collapseComments: {
		init: function(){
			var control = jQuery("#S24_commentCollapse-master");
			var comments = jQuery("#comments div.comment");
			control.unbind("click"); // make sure we don't bind twice, which breaks the feature
			
			// check cookie. By default, all comments are shown
			if(jQuery.cookie("commentCollapse") == 1){
				comments.addClass("collapsed");
				control.removeClass("shown").addClass("collapsed").html(control.attr("data-showtext"));
			}else{
				control.removeClass("collapsed").addClass("shown").html(control.attr("data-hidetext"));
			}
			
			control.click(function(){
				if(jQuery(this).hasClass("shown")){
					comments.addClass("collapsed");
					jQuery(this).removeClass("shown").addClass("collapsed").html(jQuery(this).attr("data-showtext"));
					jQuery.cookie("commentCollapse", 1, {domain: "suomi24.fi", path: "/", expires: 9999});
				}else{
					comments.removeClass("collapsed");
					jQuery(this).removeClass("collapsed").addClass("shown").html(jQuery(this).attr("data-hidetext"));	
					jQuery.cookie("commentCollapse", 0, {domain: "suomi24.fi", path: "/", expires: 9999});		
				}
			});
		}
	},
	showDelLinks: function(){ // shows the "delete" links in authenticated user's own postings
		var uid = $.cookie("DRUPAL_UID");
		if(uid){
			var counter = 1;
			var hasComm = true;
			while(hasComm){
				var delLink = $("#uid-"+uid+"-"+counter);
				if(delLink.length > 0){
					delLink.show();
					counter++;
				}else{
					hasComm = false;
				}
			}
		}
	},
	init: function(){
    if(top === self){ // if in "native Suomi24" (not inside an iframe), do the collapseComments stuff. This is because s24button doesn't offer the functionality
      Suomi24.comments.collapseComments.init();
    }
		Suomi24.comments.highlightHashComment();
		Suomi24.comments.showDelLinks();
    
    if(Suomi24.wot.enabled){
      Suomi24.wot.init();
    }
	}
}



Suomi24.columnSelector = {
	data: "/static/scripts/autocomplete_tid.php",
	initiated: false,
	init: function(input, market){		
		if(typeof(market) == "undefined"){
			market = 0;
		}
    if(!Suomi24.columnSelector.inititated){
			jQuery.getScript("/sites/all/themes/s24default/js/jquery-autocomplete.js", function(){
				Suomi24.columnSelector.events(input, market);
			});
		}
	},
	
	events: function(input, marketVal){
		var data = Suomi24.columnSelector.data;
		var idContainer = jQuery("#column-id");
		input.autocomplete(data, {
			matchContains: true,
			formatItem: function(item, index, total, query){
				return '<span id="'+item[1]+'">'+item[0]+'</span>';
			}, 
			extraParams: {
       market: marketVal
			}
		}).result(function(e, item){
			idContainer.val(item[1]);
			jQuery("#S24_column-valid").removeClass("error loading").addClass("ok");
		});
		input.change(function(){
			var resultset = jQuery("body > .ac_results li");
			if(resultset.length == 1){ // if only one result, update it to input
				idContainer.val(resultset.attr("id"));
				jQuery(this).val(resultset.text());
				jQuery("#S24_column-valid").removeClass("error loading").addClass("ok");
			}else{
				jQuery("#S24_column-valid").removeClass("ok loading").addClass("error");
			}
		});
		input.keydown(function(){
			jQuery("#S24_column-valid").removeClass("error ok").addClass("loading");
		});
		Suomi24.columnSelector.initiated = true;		
	}
}

Suomi24.emediate = {

  //check if is front
  front: location.pathname.substring(1) == 'debate' || location.pathname.substring(1) == '',

	//Emediate ads
	//the ads under the dart ads
	emediatetime: Math.round(new Date().getTime() / 1000),
	defUrl: "http://eas3.emediate.se/eas",
	template: '<script type="text/javascript" src="{@url}?{@key}"></script>',
	keys: {
	   'cu'         : this.front ? 4182 : 2837 ,
	   'cre'        : 'mu',
     'js'         : 'y',
     'target'     : '_blank',
     'c1-2-0'    : 0, // gender
     'c2-1'       : 0, // age
     'c1-4-0'     : 0, // area
     'cat1'       : 0,   //category id
     'kw'         : '0', //column name
     // weather parameters
     'EASTsouth'  : '0', 
     'EASTeast'   : '0', 
     'EASTwest'   : '0', 
     'EASToulu'   : '0', 
     'EASTlapland': '0', 
     'EASTaland'  : '0', 
     // aller packages
     'EASTpk'     : '0',
     'time'       : this.emediatetime
	},
  allerKeys:{
    'EASTpk'     : '0'
  },

	format: function (name) {
    if(name) {
       var chars = {
            'Ä' : 'A',
            'ä' : 'a',
            'Ö' : 'O',
            'ö' : 'o',
            'Å' : 'A',
            'å' : 'a'
      };
      for( var ch in chars) {
        name = name.toString().replace(new RegExp(ch,'g'),chars[ch]);
      }

      name = name.toString().toLocaleLowerCase(); //lowercase
      name = name.replace(/(^\s+|\s+$)/, '').replace(/\s/g,'_');//no space
      return name;
    } else{
      return '';
    }
  },

  /*
  sets emediate options at the beginning of page
  */
	setEmediateOption: function (categoryId, subcategory, column, kwname) {
    if(categoryId > 0){
      this.keys['cat1'] = categoryId;
      this.setEmediateAllers(categoryId);
    }
    if(subcategory[0] > 0){
      this.keys['cat1'] = subcategory[(subcategory.length)-1];
    }
    if(kwname != null){
      this.keys['kw'] = kwname;
    }
    // added to handle the userOptions
    emeUser = jQuery.cookie("emediate_user");
    if(emeUser != null){
      eUa = emeUser.split(",");
      Suomi24.emediate.setUserOptions(eUa[0], eUa[1], eUa[2], true);
    }
  },

  setEmediateAllers: function (categoryId){
    switch(categoryId){
      case "48": // Muoti ja kauneus
      case "38": // Suhteet
      case "9": // Lemmikit
      case "6054": // Työ ja opiskelu
        this.allerKeys['EASTpk'] = 'naiset|nuoret_naiset';
        break;
      case "4": // Terveys
      case "23": // Perhe
        this.allerKeys['EASTpk'] = 'naiset|terveys';
        break;
      case "7": // Koti ja rakentaminen
        this.allerKeys['EASTpk'] = 'naiset|miehet|terveys';
        break;
      case "41": // Ruoka ja juoma
        this.allerKeys['EASTpk'] = 'naiset|nuoret_naiset|terveys';
        break;
      case "6052": // Viihde
      case "52": // Ajanviete
        this.allerKeys['EASTpk'] = 'viihde';
        break;
      case "5": // Harrastukset
        this.allerKeys['EASTpk'] = 'viihde|miehet';
        break;
      case "2": // Autot ja liikenne
      case "6051": // Teknologia
        this.allerKeys['EASTpk'] = 'miehet';
        break;
      case "16": // Urheilu ja kuntoilu
      case "21": // Yhteiskunta
        this.allerKeys['EASTpk'] = 'miehet|terveys';
        break;
    }
  },
  
  /*
  sets the autenticated user options
  */
  setUserOptions: function (gender, age, area, areaIsAnumber){
    areaIsAnumber=(typeof(areaIsAnumber)=='undefined')? false : areaIsAnumber;
    if(gender == 'M'){
      this.keys['c1-2-0'] = '5';
    } else {
      this.keys['c1-2-0'] = '8';
    }
    if(age > 0){
      this.keys['c2-1'] = age;
    }
    if(areaIsAnumber){
      this.keys['c1-4-0'] = area;
    } else {
      switch(area){
        case "Ahvenanmaa":        this.keys['c1-4-0'] = 1; break;
        case "Etelä-Savo":        this.keys['c1-4-0'] = 2; break;
        case "Etelä-Karjala":     this.keys['c1-4-0'] = 4; break;
        case "Etelä-Pohjanmaa":   this.keys['c1-4-0'] = 8; break;
        case "Itä-Uusimaa":       this.keys['c1-4-0'] = 16; break;
        case "Kainuu":            this.keys['c1-4-0'] = 32; break;
        case "Kanta-Häme":        this.keys['c1-4-0'] = 64; break;
        case "Keski-Pohjanmaa":   this.keys['c1-4-0'] = 128; break;
        case "Keski-Suomi":       this.keys['c1-4-0'] = 256; break;
        case "Kymenlaakso":       this.keys['c1-4-0'] = 512; break;
        case "Lappi":             this.keys['c1-4-0'] = 1024; break;
        case "Pirkanmaa":         this.keys['c1-4-0'] = 2048; break;
        case "Pohjanmaa":         this.keys['c1-4-0'] = 4096; break;
        case "Pohjois-Karjala":   this.keys['c1-4-0'] = 8192; break;
        case "Pohjois-Pohjanmaa": this.keys['c1-4-0'] = 16384; break;
        case "Pohjois-Savo":      this.keys['c1-4-0'] = 32768; break;
        case "Päijät-Häme":       this.keys['c1-4-0'] = 65536; break;
        case "Satakunta":         this.keys['c1-4-0'] = 131072; break;
        case "Uusimaa":           this.keys['c1-4-0'] = 262144; break;
        case "Varsinais-Suomi":   this.keys['c1-4-0'] = 524288; break;
      }
    }
  },
  
  /*
  get the emediate script
  */
	getEmediateScript: function (param) {
    if(param["cu"] == "5274" || param["cu"] == "2837"){ // remove aller targeting if the cu is different than panorama / box
      this.keys["EASTpk"] = this.allerKeys["EASTpk"];
    } else {
      this.keys["EASTpk"] = '0';
    }
		for(var prop in this.keys) {
		  if(0 == this.keys[prop] || null == this.keys[prop]) delete this.keys[prop];
		  else this.keys[prop] = this.format(this.keys[prop]);//format
		}
    if(typeof(supersponsorship) != "undefined" && supersponsorship == 1){
      return '';
    }
    var str = this.template.replace('{@key}',Object.toQueryString($.extend(this.keys, param)))
    return str.replace('{@url}', arguments[1] || this.defUrl);
  },  
  
  setWeatherParameters: function(EASTsouth, EASTeast, EASTwest, EASToulu, EASTlapland, EASTaland, EASTsouth_temp, EASTeast_temp, EASTwest_temp, EASToulu_temp, EASTlapland_temp, EASTaland_temp) {
    this.keys["EASTsouth"] = EASTsouth;
    this.keys["EASTeast"] = EASTeast;
    this.keys["EASTwest"] = EASTwest;
    this.keys["EASToulu"] = EASToulu;
    this.keys["EASTlapland"] = EASTlapland;
    this.keys["EASTaland_temp"] = EASTaland;
    this.keys["EASTsouth_temp"] = EASTsouth_temp;
    this.keys["EASTeast_temp"] = EASTeast_temp;
    this.keys["EASTwest_temp"] = EASTwest_temp;
    this.keys["EASToulu_temp"] = EASToulu_temp;
    this.keys["EASTlapland_temp"] = EASTlapland_temp;
    this.keys["EASTaland_temp"] = EASTaland_temp;
  },
  
  getArgumentsForTicker: function() {
    var keys1 = {};
    for(var prop in this.keys) {
      if(0 == this.keys[prop] || null == this.keys[prop]) delete this.keys[prop];
      else keys1[prop] = this.format(this.keys[prop]);//format
    }
    //remove some key;
    delete keys1['cu'];
    delete keys1['cre'];
    delete keys1['js'];
    delete keys1['target'];
    delete keys1['time'];
    return this.toQueryString(keys1);
  }
};

Suomi24.formFieldDefaults = {
	init: function(el, text){
		el = $(el);
		if(el.length==0 || !(el instanceof jQuery)){ //abort if element doesn't exist
			return;
		}
		var form = el.closest("form");
		if(!jQuery(el).val() || jQuery(el).val() == text){ //assign default value (background image) if field has no value when page is loaded and it doesn't have focus
			jQuery(el).addClass("defaultText").val(text);
		}
		jQuery(el).focus(function(){
			if(jQuery(this).val() == text) { // if current value is the default value, then clear on focus
				jQuery(this).removeClass("defaultText").val("");
			}
		});
		jQuery(el).blur(function(){
			if(jQuery(this).val() == ""){
				jQuery(this).addClass("defaultText").val(text);
			}
		});
		form.submit(function(){
			if(el.val() == text){
				el.val("");
			}
		});
	}
};

Suomi24.forms = {
	
	tips : function(el){ // functionality for input tips (speech bubbles)
		el = $(el);
		if(el.length == 0){
			return;
		}
		
		var allTips = el.find(".text-box-tips"); // find all tip boxes
		$.each(allTips, function(i, elem){	
			elem = $(elem);
			var wrapper = elem.parent(".S24_formfield"); // the textbox may be either inside the S24_formfield or next to it in another wrapper. var wrapper = the element that holds the input
			if(wrapper.length == 0){
				var wrapper = elem.siblings(".S24_formfield");
			}
			
			var input = wrapper.find('input, textarea, select');
			if(input.length > 0){
				elem.click(function(){
					jQuery(this).addClass("fixed");
					var correctInput = input.focus();
					setTimeout(function(){allTips.removeClass("fixed");}, 300);
				});
				elem.find("a").focus(function(){
					elem.addClass("fixed");
					setTimeout(function(){allTips.removeClass("fixed");}, 300);
				});
				$(input).focus(function(){
					allTips.not(".fixed").hide();
					setTimeout(function(){elem.show();}, 300);
				});
				$(input).blur(function(){
					setTimeout(function(){allTips.not(".fixed").hide();}, 200);
				});
			}
		});
	}
}

Suomi24.forumActivityFeed = {
	init: function(object){
		if(object.length > 0) {		
			function getUpdateInterval(){ // gets a nice random interval for changing content, between 3 and 10 seconds)
				var interval = 2500 + Math.random()*5500;
				return interval;
			}
			var updateTimer;
			function updateMsgs(){
				items.eq(state+numVisible-1).fadeOut(animSpeed, function(){
					state--;
					items.eq(state).fadeIn(animSpeed);
					if(state>0){
						updateTimer = setTimeout(updateMsgs,getUpdateInterval());
					}
				});
			}
			var items = object.find("ul.S24_threadlist li");
			var numVisible = 6 ;//amount of topics shown
			var state = items.length - numVisible; //index of the first visible item
			var visible = items.slice(state, items.length).show();
			updateMsgs();
			object.hover(function(){clearTimeout(updateTimer);}, function(){updateTimer = setTimeout(updateMsgs,getUpdateInterval());})			
		}
	}
};


Suomi24.frontpageComics = {
	init: function(){
		var controls = jQuery("#S24_sarjakuvabox div.S24_sarjakuva_controls li");
		if(controls.length == 0) { // abort if item doesn't exist
			return;
		}
		this.bindEvents(controls);
	},
	bindEvents: function(controls){		
		var links = controls.find("a");
		var comics = jQuery("#S24_sarjakuvabox .S24_sarjakuva");
		
		links.each(function(){
			jQuery(this).click(function(e){
				e.preventDefault();
				/*
				WRITE COOKIE HERE!
				*/
				changeContent(jQuery(this));
			});
		});
		
		// activate default
		var default_active = controls.filter(".active").find("a"); //get link that is child of the active li-element or choose the first one
		if(default_active.length == 0){
			default_active = links.eq(0);
		}
		changeContent(default_active); 
		
		function changeContent(clicked) {
			var wanted = clicked.attr("href").split("#")[1];
			controls.removeClass("active");
			clicked.parent("li").addClass("active");
			comics.hide().filter("#S24_sarjakuva_"+wanted).show();
		}

    // --------------- next / prev buttons ---------------
    var nemi_prev = jQuery("#S24_sarjakuva_nemi button.S24_previous");
		var nemi_next = jQuery("#S24_sarjakuva_nemi button.S24_next");

		var rocky_prev = jQuery("#S24_sarjakuva_rocky button.S24_previous");
		var rocky_next = jQuery("#S24_sarjakuva_rocky button.S24_next");
		
    var comic_url = "http://www.suomi24-static.fi/sarjakuva/";
    //----------------- start by hiding next buttons 
    var lastNemi = new Date(); 
    var lastRocky =  new Date();
    while(!isNemi(lastNemi)){ lastNemi.setDate(lastNemi.getDate() - 1); }
    while(!isRocky(lastRocky)){ lastRocky.setDate(lastRocky.getDate() - 1); }
    hideNextButtons();
    
    jQuery(nemi_prev).click(function(e){
      e.preventDefault();
      previousNemi();
      hideNextButtons();
    });
    jQuery(nemi_next).click(function(e){
      e.preventDefault();
      nextNemi();
      hideNextButtons();
    });
    jQuery(rocky_prev).click(function(e){
      e.preventDefault();
      previousRocky();
      hideNextButtons();
    });
    jQuery(rocky_next).click(function(e){
      e.preventDefault();
      nextRocky();
      hideNextButtons();
    });
    
    // hides next buttons if last date
    function hideNextButtons(){
      if(jQuery("#S24_sarjakuva_nemi img").attr("data-date") == buildCleanDate(lastNemi)){
        nemi_next.hide();
      } else {
        nemi_next.show();
      }
      if(jQuery("#S24_sarjakuva_rocky img").attr("data-date") == buildCleanDate(lastRocky)){
        rocky_next.hide();
      } else {
        rocky_next.show();
      }
    }
    
    /* name = nemi / rocky */
    function getCurrComDate(name, dir){
      var curr = jQuery("#S24_sarjakuva_"+name+" img").attr("data-date");
      y = "20" + curr.substr(0,2);
      if(curr.substr(2,1) == '0'){ m = curr.substr(3,1); } else { m = curr.substr(2,2); }
      if(curr.substr(4,1) == '0'){ d = curr.substr(5,1); } else { d = curr.substr(4,2); }
      cc = new Date(parseInt(y), parseInt(m)-1, (parseInt(d) + dir), 0, 0, 0);
      if(name == 'nemi'){
        while(!isNemi(cc) ){
          cc.setDate(cc.getDate() + dir);
        }
      } else {
        while(!isRocky(cc) ){
          cc.setDate(cc.getDate() + dir);
        }
      }
      return cc;
    }
    
    // turha
    function formatNewDate(name, dir){
      cc = getCurrComDate(name,  dir);
      newDate = buildCleanDate(cc);
      return newDate;
    }
    
    // builds a string from date
    function buildCleanDate(dateO){
      var cleanDateString = "" + dateO.getFullYear();
      cleanDateString = cleanDateString.substr(2,2);
      if(dateO.getMonth() < 9){ cleanDateString = cleanDateString + "0" + (dateO.getMonth()+1); } else { cleanDateString = cleanDateString + (dateO.getMonth()+1); }
      if(dateO.getDate() < 10){ cleanDateString = cleanDateString + "0" + dateO.getDate(); } else { cleanDateString = cleanDateString + dateO.getDate(); }
      return cleanDateString;
    }
    
    // checker to check if a comic is nemi
    function isNemi(dateO){
      wDay = dateO.toString().substr(0,3);
      if(wDay == 'Fri' || wDay == 'Sat' || wDay == 'Sun'){
        return true;
      } else {
        return false;
      }
    }
    // checker to check if a comic is rocky
    function isRocky(dateO){
      wDay = dateO.toString().substr(0,3);
      if(wDay == 'Mon' || wDay == 'Tue' || wDay == 'Wed' || wDay == 'Thu'){
        return true;
      } else {
        return false;
      }
    }
    
    function previousNemi(){
      newDate = formatNewDate('nemi', -1);
			var img = jQuery("#S24_sarjakuva_nemi img");
      img.attr("src", comic_url + newDate + ".jpg");
      img.attr("data-date", newDate);
			jQuery("#S24_sarjakuva_nemi a.S24_share").attr("data-href", "/s24share/link/front?title=Nemi&url="+img.attr("src"));
    }
    
    function nextNemi(){
      newDate = formatNewDate('nemi', 1);
			var img = jQuery("#S24_sarjakuva_nemi img");
      img.attr("src", comic_url + newDate + ".jpg");
      img.attr("data-date", newDate);
			jQuery("#S24_sarjakuva_nemi a.S24_share").attr("data-href", "/s24share/link/front?title=Nemi&url="+img.attr("src"));
    }
    
    function previousRocky(){
      newDate = formatNewDate('rocky', -1);
			var img = jQuery("#S24_sarjakuva_rocky img");
      img.attr("src", comic_url + newDate + ".jpg");
      img.attr("data-date", newDate);
			jQuery("#S24_sarjakuva_rocky a.S24_share").attr("data-href", "/s24share/link/front?title=Rocky&url="+img.attr("src"));
    }
    
    function nextRocky(){
      newDate = formatNewDate('rocky', 1);
			var img = jQuery("#S24_sarjakuva_rocky img");
      img.attr("src", comic_url + newDate + ".jpg");
      img.attr("data-date", newDate);
			jQuery("#S24_sarjakuva_rocky a.S24_share").attr("data-href", "/s24share/link/front?title=Rocky&url="+img.attr("src"));
    }
	}
}	

Suomi24.frontpageHighlights = {
	init: function(){
		var links = jQuery("#S24_hotTopics li");
		if(links.length == 0) { // abort if item doesn't exist
			return;
		}
		this.bindEvents(links);	
	},
	bindEvents: function(o){ 
		var pageHeaders = jQuery("#S24_maincol div.S24_page_header");
		var contents = jQuery("#S24_maincol div.S24_highlight_cont");
		var current = 0; // sequencial number of the currently visible content
		o.each(function(){
			jQuery(this).click(function(e){
				e.preventDefault();
				changeContent(o.index(jQuery(this)));
			});
		});
		// override default active content, if declared in url hash)
		var wanted = parseInt(window.location.hash.substr(6));
		if(0 < wanted && wanted < 5){ // if hash correctly declared
			changeContent(wanted);
		}else{
			//make sure first is shown and active
			pageHeaders.removeClass("active");
			contents.removeClass("active");
			o.removeClass("active");
			pageHeaders.eq(0).addClass("active");
			contents.eq(0).addClass("active");
			o.eq(0).addClass("active");
		}
		
		function changeContent(index) {
			if(index != current){
				pageHeaders.removeClass("active");
				contents.removeClass("active");
				pageHeaders.eq(index).addClass("active");
				contents.eq(index).addClass("active");
				o.removeClass("active");
				o.eq(index).addClass("active");
			
				current = index;
				
				// Update hash
				window.location.hash = "#topic"+index;
			}
		}
	}
}

Suomi24.header = {
	searches: {
		init : function() {
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchKartatText"), "Alue, kunta, postinumero tai katuosoite");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchHenkilotText1"), "Nimi tai puhelinnumero");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchHenkilotText2"), "Alue, kunta tai osoite");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchReititText1"), "Lähtöpaikka");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchReititText2"), "Määränpää");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchKeltaisetSivutText1"), "Yritys, hakusana");
			Suomi24.formFieldDefaults.init(jQuery("#S24_searchKeltaisetSivutText2"), "Alue, kunta, postinumero");
			// Eniro doesn't like empty search parameters, they need "-" if the field is empty
			jQuery("#S24_searchHenkilot > form, #S24_searchYrityshaku > form").submit(function(){
				var inputs = jQuery(this).find("#S24_searchHenkilotText2, #S24_searchKeltaisetSivutText2");
				inputs.each(function(){
					if(jQuery(this).val() == "") {
						jQuery(this).val("-");
					}
				});
			});
			this.tabs();
			this.siteSearch();
		},
		tabs : function() {
			jQuery('#S24_headerSearch .S24_tabs a').click(function(e) {
				var _gaq = _gaq || []; 
        _gaq.push(['_trackEvent', 'EniroSearch', 'switched-tab']);
				var hash = this.hash.split('#')[1];
				jQuery('.S24_searchfield').hide();
				jQuery('#S24_search' + hash).show();
				jQuery('#S24_headerSearch li').removeClass('active');
				jQuery(this).parent().addClass('active');
				e.preventDefault();
			});
		},
		siteSearch : function() {
			jQuery("#S24_headerSearch form").submit(function(e) {
				var _gaq = _gaq || []; 
        _gaq.push(['_trackEvent', 'EniroSearch', 'searched']);
			});
		}
	},
	mina: {
		init : function() {
			var container = jQuery("#S24_headerProfile");
			this.popup(container);
			Suomi24.mina.mood.init(container);
			//this.dropdowns(container);
		},
		popup : function(container) {
			var activator = container.find("#S24_status-bubble-triggerer");
			var popup = container.find("#S24_update_status-bubble");
			activator.click(function(e){
				popup.show();
				var textarea = popup.find("textarea").focus();
				
				// remove ajax-bubble
				Suomi24.ajaxBubble.clearBubbles();
				
				// remove popup when clicking outside
				
				// IE is bad on old jQuery version
				var outsideClickEl = jQuery(document);
				if(ie && jQuery().jquery == "1.3.2"){
					outsideClickEl = jQuery("body");
				}
				outsideClickEl.click(function(ev){ // document works for good browsers and new version of 
					// only close if clicked with left button or by jquery click trigger (also to prevent firefox bug)
					if((!(ev.which != 1) || typeof(ev.which) == "undefined") && !jQuery(ev.target).is("#S24_status-bubble-triggerer")){
						popup.hide();
					}
				});	
				popup.click(function(ev){
					ev.stopPropagation();
				});
				
				popup.find("button[type=reset]").click(function(){
					popup.hide();
				});
				
				//prevent sending empty update
				popup.find("form").submit(function(){
					if(textarea.val() == ''){
						var errorCont = popup.find("#S24_error-cont").html(Drupal.t('Kirjoita kuulumiset yllä olevaan tekstikenttään'));
						textarea.keydown(function(){
							errorCont.html('');
						});
						return false;
					}else{
						return true;
					}
				});
			});
		},
		dropdowns: function(container) {
			var activators = container.find(".S24_notifications > div > div");
			activators.each(function(){
				jQuery(this).click(function(e){
					e.preventDefault();
					if(jQuery(this).parent().hasClass("active")){
						activators.parent().removeClass("active");
					} else {
						activators.parent().removeClass("active");
						jQuery(this).parent().addClass("active");
					}
					
					// remove dropdown when clicking outside
					e.stopPropagation();
					jQuery(document).click(function(){
						activators.parent().removeClass("active");
					});
					activators.find("ul").click(function(ev){
						ev.stopPropagation();
					});	
				});
			});
		}
	},
	init: function() {
		// user control stuff
		/*
		Obsolete, replaced by Cache Control implementation
		if(uid > 0){ // if logged in, get Minä stuff
			jQuery("#loginboxload").html('<div id="#S24_headerProfile">');
			
			jQuery.get('/s24pfcoreheader/loginbox/'+uid+'/'+hash, function(data){
				// add wanted_url to logout link
				loginbox = jQuery(data);
				var logoutlink = loginbox.find("#S24_logoutlink");
				logoutlink.attr('href', logoutlink.attr('href')+'?wanted_url='+wanted_url);
				
				jQuery("#loginboxload").html(loginbox).css({visibility: "visible"});
				Suomi24.header.mina.init();
			});
		}else{ // anonymous user 
			jQuery("#loginboxload").css({visibility: "visible"});
		}
		*/
		
		//searches 
		// this.searches.init();	
		
		//Suomi24.formFieldDefaults.init(jQuery("#S24_update_status-bubble textarea"), "Mitä sinulle kuuluu? Kirjoita tähän...");
		
    Suomi24.formFieldDefaults.init(jQuery("#S24_username"), "Käyttäjätunnus");
		Suomi24.formFieldDefaults.init(jQuery("#S24_password"), "Salasana");
		
    // page-specific stuff
		if(jQuery("body").hasClass("s24_frontpage")){ // prepare www frontpage for block ordering
			jQuery("body").addClass("frontpageLoading");
		}
		else if(jQuery("body").hasClass("node-type-forum")){ // count thread page views
			var nid = jQuery("body").attr("data-nid");
			$.ajax({
				type: 'GET',
				url: '/listmessage/'+nid+'/click_count',
				success: function(html){ if (html != 'KO') jQuery("#topic-views-"+nid).html(html); }
			});
		}
    
    if(mobileBrowser){
      jQuery("body").addClass("mobile");
    }
	}
};

Suomi24.hissi = {
	init: function(cont){
		var topmargin = 8;
		var banner = cont.find(".S24_banner");
		var refobj = jQuery("#S24_maincol");
		var motherobj = jQuery("#S24_leftcol");
		var blockobj = jQuery("#S24_footer");
		if(banner.length > 0) { 
			cont.css("position", "relative");
			banner.css({position: "relative"});
			
			if(jQuery.browser.mozilla){ // Because FF wants to restart flash whenever it's certain attributes are changed, we need a special fix
				banner.parent().css({minHeight: banner.height()+topmargin+10+"px"});
				$(window).scroll(function(){
					banner.css({position: "fixed"});
					if(refobj.height() > motherobj.height()){
						var diff = cont.offset().top - $(window).scrollTop() + topmargin;
						if($(window).scrollTop() > (refobj.offset().top + refobj.height() - banner.height() - topmargin)){ // if would come out of bounds
							diff = refobj.offset().top + refobj.height() - banner.height() - topmargin - $(window).scrollTop();
							banner.css({top: diff});
						}else if(diff < 0){ // if should be scrolled
							banner.css({top: topmargin});
						}else{ // if not needed to scroll yet
							banner.css({top: cont.offset().top - $(window).scrollTop() + topmargin});
						}
					}else{
						banner.css({top: cont.offset().top - $(window).scrollTop() + topmargin});
					}
				});
					
			}else{ // other browsers are nicer	
				$(window).scroll(function(){	
					var pos = $(window).scrollTop()-cont.offset().top + topmargin;
					if(pos <= 0){ // if no need to move yet
						banner.css({position: "relative", top: 0, left: "auto"});
					}else if(pos > (refobj.offset().top + refobj.height() - cont.offset().top - banner.height() - topmargin)){ // if would come on top of full-width elements before footer (eg. frontpage comics and links)
						pos = refobj.offset().top + refobj.height() - cont.offset().top - banner.height() - topmargin;
						banner.css({position: "relative", top: pos, left: "auto"});
					} else if ($(window).scrollTop() > blockobj.offset().top - banner.height() - topmargin){ // if would come over footer
						pos = blockobj.offset().top - cont.offset().top - banner.height() - topmargin;
						banner.css({position: "relative", top: pos, left: "auto"});
					}
					else {
						if(ie7){
							banner.css({position:"fixed", top: topmargin, left: cont.offset().left + 1});
						}else{
							banner.css({position:"fixed", top: topmargin});
						}
					}
				});
			}
		}
	}
}

Suomi24.horoscope = {
  init : function() {
	  var container = jQuery("#S24_horoskoopitbox");
	  var buttonCont = jQuery(".S24_horoscope_buttons", container);
	  var allDivs = jQuery("div", container);
	  this.bindEvents(buttonCont, allDivs);
  },
  bindEvents: function(buttons, allDivs){
	  buttons.find("div").each(function(){
	    jQuery(this).click(function(e){
		  e.preventDefault();
	      allDivs.removeClass("active");
	      allDivs.filter("."+jQuery(this).attr("id")).addClass("active");
	    });
	  });
	  allDivs.find("a").each(function(){
	    jQuery(this).click(function(e){
		  e.preventDefault();
		  allDivs.removeClass("active");
		  buttons.addClass("active");
	    });
	  });
  }
};

Suomi24.kalenteri = {
  init : function() {
	  var container = jQuery("#S24_kalenteribox");
	  this.bindEvents(container);
  },
  bindEvents: function(container){
	  var nextButton = container.find("span.S24_arrowright");
	  var prevButton = container.find("span.S24_arrowleft");	
		var date = container.find("#S24_kalenteri_date");
		var events = container.find("#S24_kalenteri_events");
		var both = jQuery("#S24_kalenteri_date, #S24_kalenteri_events");
		var	dateHead = date.find("time");
		var nimipaivat = date.find(".S24_kalenteri_nimipaivat ul");
		var toLink = container.find("#to_wikipage");
		
		nextButton.click(function() {
			changeDate(1);
		});
		prevButton.click(function() {
			changeDate(0);
		});
		
		function changeDate(next){
			var loader = container.addLoadingImg();
			both.fadeTo(100, 0);
      var	dateCurr = container.find("#S24_kalenteri_date time").attr("datetime");
      jQuery.get("/tools/getdate/"+dateCurr+'/'+next+'/1', function(data){
        var crap = jQuery.parseJSON(data);
				events.find("ul").html(crap.events);
        dateHead.html(crap.head);
				nimipaivat.html(crap.names);
        dateHead.attr("datetime", crap.curr);
				toLink.attr("href", crap.wikilink);
				loader.remove();
				both.fadeTo(animSpeed/5, 1);
			});
		}
  }
};

var getFeedInitiated = false;
Suomi24.mina = {
	// mood updater
	mood: {
		init: function(context) {
			if(typeof(context)=="undefined") {
				context="";
			}
			
			var container = jQuery("div.S24_mina_status_mood", context);
			if(container.length == 0) { // abort if item doesn't exist
				return;
			}
			this.bindEvents(container);
		},
		bindEvents: function(a) {	
			a.each(function(){
				var o = jQuery(this);
				var current = o.find("div.S24_mina_status_mood_current");
				var button = o.find("div.S24_mina_status_mood_button")
				var selector = o.find("div.S24_mina_status_mood_selector");
				var clickarea = o.find("div.S24_mina_status_mood_current, div.S24_mina_status_mood_button");
				
				clickarea.click(function(e){
					selector.toggle();
				});
				
				selector.find("li").each(function(){ // when a li element in selector is clicked, change mood
					jQuery(this).click(function(){
						switchMood(jQuery(this));
					});
				});
				
				function switchMood(li){
					current.html(li.find('img').clone()); // change current image
					var moodId = li.attr("id").split('-')[1]; 
					jQuery('#S24_edit-fbss-status-mood', o).val(moodId); // change hidden input value
					selector.hide();

				}
			});
		}
	},
	activity: {
		init: function(context){
			if(!getFeedInitiated){
				var activityBox = jQuery('#S24_mina_activity', context);
				if(activityBox.length > 0) {
					this.bindEvents(activityBox);
				}else{
					return false;
				}
			}
			getFeedInitiated = true;
		},
		bindEvents: function(activityBox){
			 jQuery.get("/s24minahelper/getfeed/0", function(data) {
					activityBox.empty();
					if(data != null){
						commentable = data['commentable'];
						data = data['statuses'];
						var statuses_updated = false;
            for(var i in data) {
							if(i >= 5){
								break;
							}
							var d = '<li><img class="S24_pic_thumb" alt="" src="' + data[i].profile_url + '"/><div><span>'+ data[i].message+'</span><time datetime="YYYY-MM-DDTHH:MM+02:00">' + data[i].timestamp + '</time></div></li>';
							activityBox.append(d);
              statuses_updated = true;
						}
            if(statuses_updated == false){
							var d = '<li>Ei tapahtumia</li><li> </li>';
							activityBox.append(d);
            }
					}
				},
				"json"
			);
			
		}
	},
	vcard: {
		init: function(context){
			if(typeof(context) == "undefined"){
				context = jQuery(document);
			}else{
				context = jQuery(context);
			}
			var vcards = jQuery(".S24_mina-vcard", context);
			
			var timer;
			
			if(ie){
				var cloneCont = jQuery("body").append("<div id='vcard-clone-container'></div>");
				vcards.parent().hover(function(){
					refVcard = $(this).find("div.S24_mina-vcard");
					var vcard = jQuery("#"+refVcard.attr("id")+"-clone");
					if(vcard.length < 1){
						var vcard = refVcard.clone()
						vcard.appendTo(cloneCont).attr("id", vcard.attr("id")+"-clone");
					}
					if(!vcard.is(":visible")){
						var vcardId = vcard.attr("id");
						// Position correctly
						var parentpos = $(this).offset();
						
						vcard.css({left: parentpos.left + $(this).width()/2 , top: parentpos.top - vcard.height()+13});
						vcard.hover(function(){
							jQuery(this).show();
						}, function(){
							jQuery(this).hide();
						});
						timer = setTimeout("$('#"+vcardId+"').show()", 400);
					}
				},function(){
					clearTimeout(timer);
					cloneCont.children("div.S24_mina-vcard").hide();
				});
			}else{				
				vcards.parent().hover(function(){
					var vcard = $(this).find("div.S24_mina-vcard");
					vcard.css({top: 0-vcard.height()});
					var vcardId = vcard.attr("id");
					timer = setTimeout("$('#"+vcardId+"').fadeIn(200)", 300);
				},function(){
					clearTimeout(timer);
					$(this).find("div.S24_mina-vcard").fadeOut(animSpeed/2);
				});
				vcards.mouseover(function(e){
					$(this).show();
					e.stopPropagation();
				});
			}
		}
	},
	
	vcard_new: {
		init: function(context){
			if(typeof(context) == "undefined"){
				context = jQuery(document);
			}else{
				context = jQuery(context);
			}
			
			//var vcards = jQuery(".S24_mina-vcard", context);
			
			var imgContainers = jQuery(".S24_pic", context);
			
			var timer, timeout, request;
			
			if(ie) { // for Internet Explorer
				var cloneCont = jQuery("body").append("<div id='vcard-clone-container'></div>");
				imgContainers.hover(function(e) {					
					if($('.S24_mina-vcard', this).length == 0) {
						var uid = $(this).attr('data-uid');
						if(uid == undefined) {
							return false;
						}
						
						timeout = setTimeout(function() {
							
							request = $.ajax({
								url: Drupal.settings.basePath + 's24_mina/vcard/' + uid,
								success: function(data) {
									//console.log(data);
									if(data.success == 1) {
										//console.log(e);
										$(e.currentTarget).append(data.markup);
										
										refVcard = $(e.currentTarget).find('div.S24_mina-vcard');
										var vcard = jQuery("#"+refVcard.attr("id")+"-clone");
	
										if(vcard.length < 1){
											var vcard = refVcard.clone()
											vcard.appendTo(cloneCont).attr("id", vcard.attr("id")+"-clone");
										}
										if(!vcard.is(":visible")){
											var vcardId = vcard.attr("id");
											// Position correctly
											var parentpos = $(this).offset();
											
											vcard.css({left: parentpos.left + $(this).width()/2 , top: parentpos.top - vcard.height()+13});
											vcard.hover(function(){
												jQuery(this).show();
											}, function(){
												jQuery(this).hide();
											});
											timer = setTimeout("$('#"+vcardId+"').show()", 400);
										}
										
									}
								},
								dataType: "json"
							});
						
						}, 500);					
						
					}
					else {
						// vcard already there
						refVcard = $(this).find("div.S24_mina-vcard");
						var vcard = jQuery("#"+refVcard.attr("id")+"-clone");
						if(vcard.length < 1){
							var vcard = refVcard.clone()
							vcard.appendTo(cloneCont).attr("id", vcard.attr("id")+"-clone");
						}
						if(!vcard.is(":visible")){
							var vcardId = vcard.attr("id");
							// Position correctly
							var parentpos = $(this).offset();
							
							vcard.css({left: parentpos.left + $(this).width()/2 , top: parentpos.top - vcard.height()+13});
							vcard.hover(function(){
								jQuery(this).show();
							}, function(){
								jQuery(this).hide();
							});
							timer = setTimeout("$('#"+vcardId+"').show()", 400);
						}
					}
				}, function() {
					clearTimeout(timer);
					cloneCont.children("div.S24_mina-vcard").hide();
				});

			}
			else { // for other browsers
				imgContainers.hover(function(e) {
					if($('.S24_mina-vcard', this).length == 0) {
						var uid = $(this).attr('data-uid');
						if(uid == undefined) {
							return false;
						}
						
						// @todo: also don't do anything is hovering on an own image
						
						//var uid = 1;
						
						timeout = setTimeout(function() {
						
							request = $.ajax({
								url: Drupal.settings.basePath + 's24_mina/vcard/' + uid,
								success: function(data) {
									//console.log(data);
									if(data.success == 1) {
										//console.log(e);
										$(e.currentTarget).append(data.markup);
										var vcard = $(e.currentTarget).find('div.S24_mina-vcard');
										
										vcard.mouseover(function(ev){
											$(this).show();
											ev.stopPropagation();
										});
										
										vcard.css({top: 0-vcard.height()});
										var vcardId = vcard.attr("id");
										//timer = setTimeout("$('#"+vcardId+"').fadeIn(200)", 300);
										$('#'+vcardId).fadeIn(200);
									}
								},
								dataType: "json"
							});
						
						}, 500);
						
					}
					else {
						//console.log('vcard there already');

						var vcard = $(this).find('div.S24_mina-vcard');

						vcard.mouseover(function(ev){
							$(this).show();
							ev.stopPropagation();
						});
						
						vcard.css({top: 0-vcard.height()});
						var vcardId = vcard.attr("id");
						timer = setTimeout("$('#"+vcardId+"').fadeIn(200)", 300);						
					}
				}, function(e) {
					//console.log('out');
					clearTimeout(timeout);
					clearTimeout(timer);
					$(e.currentTarget).find("div.S24_mina-vcard").fadeOut(animSpeed/2);
				});
			}
		}
	},
	
	init: function(context, uid) {
		this.mood.init(context);
		this.activity.init(context, uid);
	}
}

Suomi24.oma = {
	privacySettingsForm: {
		init: function(){
			var hideOptions = jQuery("#edit-privacy-profile-1, #edit-privacy-profile-2");
			var origSwitch = hideOptions.filter("[checked]");
			var hideSwitch = jQuery("#S24_hideprofile-switch").show();
			var hideSwitchBox = jQuery("#S24_hideprofile-switch-check");
			var settingsDiv = jQuery("#S24_privacy-settings");
			jQuery("#edit-privacy-profile-0-wrapper").hide();
			
			var allSwitch = jQuery("#edit-privacy-profile-1-wrapper input");
			var friendsSwitch = jQuery("#edit-privacy-profile-2-wrapper input");
			
			if(jQuery("#edit-privacy-profile-0").is(":checked")){
			  hideSwitchBox.attr("checked", "checked");
				hideProfile();
			}
     
			hideSwitchBox.change(function(){
				if(jQuery(this).is(":checked")){
					hideProfile();
				}else{
					showProfile();
				}
			});
			
			hideOptions.change(function(){
				switchSetting(jQuery(this).val());
			});
			function switchSetting(value){
				$("#edit-show-status-update-"+value+", #edit-privacy-friendlist-"+value+", #edit-privacy-guestbook-write-"+value+", #edit-privacy-privmsg-"+value).click();
			}
			
			function hideProfile(){
				origSwitch = hideOptions.filter("[checked]");
				//pfcore-266 modifed by ruchi
				origSwitchval = origSwitch.val();
				jQuery("#edit-prev-visibility").val(origSwitchval);
				//End pfcore-266 
				jQuery("#edit-privacy-profile-0").attr("checked", "checked");
				hideSwitchBox.attr("checked", "checked");
				settingsDiv.addClass("hide");
				settingsDiv.find("input").not("#edit-privacy-profile-0 , #edit-prev-visibility").attr("disabled", "disabled");//pfcore-266 modifed by ruchi			
      }
			function showProfile(){	
				//pfcore-266 modifed by ruchi
				origSwitchval = jQuery("#edit-prev-visibility").val();
				if(origSwitchval == 1){
					origSwitch = jQuery("#edit-privacy-profile-1");
				}
				else{
					origSwitch = jQuery("#edit-privacy-profile-2");
				}	
				//end pfcore-266
				origSwitch.attr("checked", "checked");
				settingsDiv.removeClass("hide");
				settingsDiv.find("input").removeAttr("disabled");
			}
		}		
	}
}

Suomi24.partner = {
	init: function(wrapper, clickCounter) {
		if(wrapper.length == 0) {
			return;
		}
		this.bindEvents(wrapper, clickCounter);
	},
	bindEvents: function(o, clickCounter){
		var form = o.find("form");
		form.submit(function(e){
			e.preventDefault();
			var action = jQuery(this).attr("action");
			var loading = o.addLoadingImg();
			var vars=jQuery(this).serialize();
			jQuery.post(action, vars, function(data){  
				loading.remove();
				o.find(".S24_block_content").removeClass("active");
				o.find(".S24_block_content.S24_dynamic-"+data).addClass("active");
				o.find(".S24_click_counter").html("<img src='"+clickCounter+"' alt='' />");
			});
			return false;
		});
	}
}

Suomi24.profanity = {
	deactivated: false, // is the feature turned off on the page
	init: function(context) {
		Suomi24.profanity.bindToolbox();
		// if profanity filtering turned off, don't continue from here
		if(Suomi24.profanity.deactivated || jQuery.cookie("profanity_off") == 1){
			return;
		}
		jQuery("body").addClass("S24_profanity");
		
		if(typeof(context) == "undefined"){
			context = jQuery(document);
		}
		var items = jQuery("span.s24_profanity", context); // search for ugly words
				
		// if no ugly words found, abort mission
		if(items.length == 0) {
			jQuery("body").removeClass("S24_profanity");
			return;
		}
		
		// If the first time (no cookie), create the notification and the functionality to the top of page (only if not there already)
		var profNotice = jQuery("#S24_profanity-note");
		if(profNotice.length == 0 && jQuery.cookie("profanity_off") == null){
			profNotice = jQuery("#S24_maincol").prepend('<div class="notice" id="S24_profanity-note">'+Drupal.t('Tältä sivulta on sensuroitu kirosanoja')+'<div id="S24_profanity-links"><ul class="S24_horizontal"><li><span class="S24_profanity-show">'+Drupal.t('Näytä koko sivu alkuperäisessä muodossa')+'</span></li><li><span class="S24_profanity-off">'+Drupal.t('Poista sensurointi käytöstä')+'</span></li></ul></div></div>');
			
			// bind actions to the notification
			profNotice.find("span.S24_profanity-show").live("click", function(){
				Suomi24.profanity.showProfanity(items);
				Suomi24.profanity.deactivated = true;
				jQuery(this).removeClass("S24_profanity-show").addClass("S24_profanity-hide").html(Drupal.t("Näytä koko sivu sensuroituna"));
			});
			profNotice.find("span.S24_profanity-hide").live("click", function(){
				Suomi24.profanity.deactivated = false;
				Suomi24.profanity.bindEvents(items);
				jQuery(this).removeClass("S24_profanity-hide").addClass("S24_profanity-show").html(Drupal.t("Näytä koko sivu alkuperäisessä muodossa"));
			});
			profNotice.find("span.S24_profanity-off").live("click", function(){
				Suomi24.profanity.showProfanity(items);
				jQuery.cookie("profanity_off", 1);
				jQuery(this).removeClass("S24_profanity-off").addClass("S24_profanity-on").html(Drupal.t("Ota sensurointi käyttöön"));
				jQuery('#S24_profanity-switch').removeClass("S24_profanity-off").addClass("S24_profanity-on").html(Drupal.t('<a>'+Drupal.t("Ota sensurointi käyttöön")+'</a>'));
			});
			profNotice.find("span.S24_profanity-on").live("click", function(){
				Suomi24.profanity.deactivated = false;
				Suomi24.profanity.bindEvents(items);
				jQuery.cookie("profanity_off", 0);
				jQuery(this).removeClass("S24_profanity-on").addClass("S24_profanity-off").html(Drupal.t("Poista sensurointi käytöstä"));
				jQuery('#S24_profanity-switch').removeClass("S24_profanity-on").addClass("S24_profanity-off").html(Drupal.t('<a>'+Drupal.t("Poista sensurointi käytöstä")+'</a>'));
				profNotice.find('span.S24_profanity-hide').removeClass("S24_profanity-hide").addClass("S24_profanity-show").html(Drupal.t("Näytä koko sivu alkuperäisessä muodossa"));
			});
		}
		// bind the hover events to cleaned words
		this.bindEvents(items);
	},
	
	
	bindToolbox: function(){	// bind the controls in tools section
		toolbox = jQuery("#S24_maincol > .S24_page_header .S24_tools");
		
		// if there already, don't do it
		if(toolbox.find("#S24_profanity-switch").length > 0){
			return;
		}
		
		if(jQuery.cookie("profanity_off") == 1){
			toolbox.find("ul").append('<li id="S24_profanity-switch" class="S24_profanity-on"><a>'+Drupal.t('Ota sensurointi käyttöön')+'</a></li>');
		}else{
			toolbox.find("ul").append('<li id="S24_profanity-switch" class="S24_profanity-off"><a>'+Drupal.t('Poista sensurointi käytöstä')+'</a></li>');			
		}

		toolbox.find("#S24_profanity-switch.S24_profanity-off a").live("click", function(){
			jQuery.cookie("profanity_off", 1);
			Suomi24.profanity.showProfanity($("span.s24_profanity"));
			jQuery('#S24_profanity-note span.S24_profanity-off').removeClass("S24_profanity-off").addClass("S24_profanity-on").html(Drupal.t("Ota sensurointi käyttöön"));
			jQuery(this).parent().removeClass("S24_profanity-off").addClass("S24_profanity-on").html('<a>'+Drupal.t("Ota sensurointi käyttöön")+'</a>');
		});
		toolbox.find("#S24_profanity-switch.S24_profanity-on a").live("click", function(){
			jQuery.cookie("profanity_off", 0);
			Suomi24.profanity.deactivated = false;
			Suomi24.profanity.init();
			jQuery('#S24_profanity-note span.S24_profanity-on').removeClass("S24_profanity-on").addClass("S24_profanity-off").html(Drupal.t('<a>'+Drupal.t("Poista sensurointi käytöstä")+'</a>'));
			jQuery(this).parent().removeClass("S24_profanity-on").addClass("S24_profanity-off").html('<a>'+Drupal.t("Poista sensurointi käytöstä")+'</a>');
			jQuery('#S24_profanity-note span.S24_profanity-hide').removeClass("S24_profanity-hide").addClass("S24_profanity-show").html(Drupal.t("Näytä koko sivu alkuperäisessä muodossa"));
		});
	},
	
	bindEvents: function(items){ // bind controls to the ugly words
		var profanityCont = $('#profanity-tools-container'); // a 'sandbox' for popups, create if not already present
		if(profanityCont.length == 0){
			profanityCont = jQuery("body").append("<div id='profanity-tools-container'>");
		}
		var timer;
		var popupContent = '<span>'+Drupal.t('Tältä sivulta on sensuroitu kirosanoja')+'</span><ul><li><span class="S24_profanity-message-show">'+Drupal.t('Näytä alkuperäinen teksti')+'</span></li><li><span class="S24_profanity-show">'+Drupal.t('Näytä koko sivu alkuperäisessä muodossa')+'</span></li><li><span class="S24_profanity-off">'+Drupal.t('Poista sensurointi käytöstä')+'</span></li></ul>';
		
		items.each(function(){ // go through the profanity spans and do magic
			jQuery(this).html(jQuery(this).attr("data-nice")).addClass("nice");
			
			jQuery(this).hover(function(){
				var hovered = jQuery(this);
				var profanityToolbox;
				
				// if popup not already created, do it now
				if(typeof(!hovered.attr('id')) == 'undefined' || hovered.attr('id') == ''){
					hovered.attr('id', Math.floor(Math.random()*1000000)); // make id to enable matching the word with popup (also to make note that popup is created)
					profanityToolbox = jQuery('<div class="profanity-tools" data-id="'+hovered.attr('id')+'"><div class="profanity-tools-inner">'+popupContent+'</div></div>').appendTo(jQuery("#profanity-tools-container")); // create content of the popup
					
					// Position correctly
					var parentpos = hovered.offset();
					var topPos = parentpos.top - profanityToolbox.height();
					var leftPos = parentpos.left + hovered.width()/2;
					profanityToolbox.css({left: leftPos, top: topPos });
					// make sure the popup stays visible on hover
					profanityToolbox.hover(function(){
						jQuery(this).show();
					}, function(){
						jQuery(this).hide();
					});
					
					//bind actions to links
					profanityToolbox.find("span.S24_profanity-message-show").click(function(){
						Suomi24.profanity.showProfanity(hovered.parent().find('.s24_profanity'));
						jQuery(this).addClass("disabled");
					});
					profanityToolbox.find("span.S24_profanity-show").click(function(){
						Suomi24.profanity.showProfanity(items);
						Suomi24.profanity.deactivated = true;
						jQuery('#S24_profanity-note span.S24_profanity-show').removeClass("S24_profanity-show").addClass("S24_profanity-hide").html(Drupal.t("Näytä koko sivu sensuroidussa muodossa"));
					});
					profanityToolbox.find("span.S24_profanity-off").click(function(){
						Suomi24.profanity.showProfanity(items);
						jQuery(this).addClass("disabled");
						jQuery.cookie("profanity_off", 0);
						jQuery('#S24_profanity-note span.S24_profanity-off').removeClass("S24_profanity-off").addClass("S24_profanity-on").html(Drupal.t("Ota sensurointi käyttöön"));
						jQuery('#S24_profanity-switch').removeClass("S24_profanity-off").addClass("S24_profanity-on").html(Drupal.t('<a>'+Drupal.t("Ota sensurointi käyttöön")+'</a>'));
					});	
					
				}else{ // if popup already exists, just find it
					profanityToolbox = jQuery('#profanity-tools-container').find('div[data-id='+hovered.attr('id')+']');
				}
				
				// if not already visible, show it
				if(!profanityToolbox.is(":visible")){
					jQuery('#profanity-tools-container .profanity-tools').hide(); // hide others

					timer = setTimeout(function(){profanityToolbox.fadeIn(100)}, 400); // show with delay
					jQuery(this).click(function(){ // on click, show without delay
						clearTimeout(timer);
						profanityToolbox.fadeIn(100);
					});
				}
				
			},function(){ // hover out
				clearTimeout(timer);
				profanityCont.find("div.profanity-tools").hide();
			});
			
			jQuery(this).removeClass("ugly").addClass("cleaned");
		});
	},
	
	// show the original version of cleaned words (parameter: the jQuery object containing the spans to be uncleaned)
	showProfanity: function(object){
		object.each(function(){
			jQuery(this).html(jQuery(this).attr("data-bad")).removeClass("cleaned").addClass("ugly").unbind('mouseenter mouseleave')
		});
		return object;
	}
}

Suomi24.share = {
	init: function(wrapper) {
		if(wrapper.length == 0){ //abort if no tabs exist
			return;
		}
		this.bindEvents(wrapper);
		wrapper.find("ul.S24_share-options li.active a").click(); 
	},
	bindEvents: function(o){		
		//share option links
		var allcont = o.find(".S24_share-options-cont > div");
		var alltabs = o.find("ul.S24_share-options li");
		alltabs.find("a").each(function(){
			jQuery(this).click(
				function (e) {
					e.preventDefault();
					var li = jQuery(this).parent();
					var cont=allcont.filter("."+li.attr("data-correspond"));
					if(cont.length > 0){ // if should show a form inline
						alltabs.removeClass("active");
						li.addClass("active");
						allcont.hide();
						cont.show();
					}else{  // if should popout a form (Facebook, Twitter)
						if(li.hasClass("S24_share-fb")){ //fb
              window.open(li.find("a").attr("href"), "facebook","toolbar=no,scrollbars=yes,menubar=no,status=no,directories=no,width=990,height=400");
							jQuery("body").click();
						}else if(li.hasClass("S24_share-twitter")){
              window.open(li.find("a").attr("href"), "twitter","toolbar=no,scrollbars=no,menubar=no,status=no,directories=no,width=480,height=270");
							jQuery("body").click();
						}
					}
					jQuery(this).addClass("active");
				});
		});
		
		//copy to clipboard functionality (ie only)
		if(ie) {
			var urlinput = o.find(".S24_share-url input[name=url]");
			var copybutton = o.find(".S24_share-url button").click(function(){
				window.clipboardData.setData('Text', urlinput.select().val());
			});
			copybutton.parent("S24_textfield").addClass("S24_search");
		}
		
		// reset = close bubble
		allcont.find("button[type=reset]").click(function(ev){
			jQuery("body").click();
		});
    
	}, 
  validEmail: function(emailaddressVal){
    var emailReg = /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i;
    if(emailReg.test(emailaddressVal)) {
      return false;
    } else {
      return true;
    }
  },
  checkEmail: function (field){
    var allok = true;
    emailaddressVal = jQuery("#"+field).val();
    var p = emailaddressVal.split(",");
    for(var i = 0;i < p.length;i++){
      if(Suomi24.share.validEmail(p[i].trim())){
        allok = false;
      }
    }
    if(allok){
      jQuery('#'+field+'-check').removeClass("error");
      jQuery('#'+field+'-check').addClass("ok");
    } else {
      jQuery('#'+field+'-check').removeClass("ok");
      jQuery('#'+field+'-check').addClass("error");
    }
  },
  // email form submitting
  submitShareForm: function (form_name){
    var form = jQuery(form_name);
    var action = form.attr("action");
    jQuery.ajax({
      type: 'POST',
      url: action,
      data: form.serialize(),
      success: function(data){
        var ferror = 0;
        // loading ok error
        jQuery('#edit-mail-list-check, #edit-mail-self-check, #form-alert').removeClass("ok");
        jQuery('#edit-mail-list-check, #edit-mail-self-check, #form-alert').removeClass("error");
        
        if(data.errors.mail_list != null){
          jQuery('#edit-mail-list-check').addClass("error"); ferror = 1;
        } else {
          jQuery('#edit-mail-list-check').addClass("ok");
        }
        if(data.errors.mail_self != null){
          jQuery('#edit-mail-self-check').addClass("error"); ferror = 1;
        } else {
          jQuery('#edit-mail-self-check').addClass("ok");
        }
        if(ferror == 1){
          jQuery('#form-alert').addClass("error");
        } else {
          jQuery('#form-alert').addClass("ok");
          jQuery('#s24share-email-form div.S24_formfield').hide();
          jQuery('#s24share-email-form button').hide();
        }
        jQuery('#form-alert').html(data.reply);
      },
      dataType: "json"
    });
  }
}

Suomi24.styledFileInput = {
	init: function(fileInput, callback){
		if(ie){
			return;
		}
		
		if(typeof(callback) == "undefined"){
			callback = function(){};
		}
		
		fileInput = $(fileInput);
		if(fileInput.length == 0){
			return;
		}
		
		if(fileInput.prev("div.S24_styled-file-input").length == 0){
			var fakeTextInput = $("<div class='S24_textfield S24_search S24_styled-file-input'><input type='text' value='"+fileInput.val()+"'><button><span>"+Drupal.t("Selaa...")+"</span></button></div>");
		} else {
			var fakeTextInput = fileInput.prev("div.S24_styled-file-input");
		}
		
		fakeTextInput.keydown(function(){
			return false;
		});
		
		/* make sure that clicking the fake element acts like clicking the file input itself */
		inputEvent = function(e){
			fileInput.click();
			e.preventDefault();
			e.stopPropagation();
			return false;
		}
		
		fakeTextInput.click(inputEvent);
		var textInputEl = fakeTextInput.find("input").click(inputEvent);
		
		// initial value
		fakeTextInput.val(clearFakepath($(this).val()));
				
		
						
		if(fileInput.parent().css("position") != "absolute" || fileInput.parent().css("position") != "relative"){
			fileInput.parent().css({position: "relative"})
		}
		
		fileInput.fadeTo(0, 0).addClass("S24_styled-file-input").before(fakeTextInput);
		
		// size and position of the input. Since the element might not be shown yet (ajax loads), let's try a few times (max 10 times in 0.2 second intervals)
		var counter = 0;
		var checkSize = setInterval(function(){
			if(fileInput.width() > 0){ // input ready, let's do the sizing and positioning;
				fakeTextInput.width(fileInput.width());
				fileInput.css({position: "absolute", top: fakeTextInput.position().top, left: fakeTextInput.position().left })
				textInputEl.width(fakeTextInput.width()-parseInt(textInputEl.css("padding-right")));
				clearInterval(checkSize);
				callback(fileInput);
			}else	if(counter > 10){ // timeout
				clearInterval(checkSize);
				callback(fileInput);
			}else{ // not yet, let's try later
				counter++;
			}
		}, 200);
		
		
		fileInput.change(function(){ // change text input value when file is selected
			textInputEl.val(clearFakepath($(this).val()));
		});
		
		function clearFakepath(str){ // clear X:\fakepath from the path
			return str.substring(1, 12) == ":\\fakepath\\" ? str.substring(12) : str;
		}
	}
}

Suomi24.tabs = {
	init: function(wrapper){
		if(wrapper.length == 0){ //abort if no tabs exist
			return;
		}
		this.bindEvents(wrapper);
		var active = wrapper.find("ul.S24_tabs li.active a"); // search default tab (.active)
		if(active.length > 0){
			active.click(); //activate tab if class .active is set
		}else{
			wrapper.find("ul.S24_tabs li:first a").click(); // else show first tab of set
		}
	},
	bindEvents: function(o){
		o.find("ul.S24_tabs li a").click(
			function (e) {
				e.preventDefault();
				Suomi24.tabs.toggleTab(this);
			}
		);
	},
	toggleTab: function(el){
		var li = jQuery(el).parent();
		var liList = jQuery(li).parent().children();
		var index = jQuery(liList).index(li);
		var tabsWrapper = jQuery(li).parent().parent();
		var tabsContent = jQuery(tabsWrapper).find("div.S24_tabsContent");
		jQuery(liList).removeClass("active");
		jQuery(li).addClass("active");
		tabsContent.hide();
		tabsContent.eq(index).show();
	}
};


Suomi24.textsize =  {
	
	init: function(){
		var controls = jQuery("#S24_textsize");
		if(controls.length == 0){ //abort if item doesn't exist
			return;
		}
		var control_s = jQuery("#S24_textsize_s");
		var control_m = jQuery("#S24_textsize_m");
		var control_l = jQuery("#S24_textsize_l");
		
		this.bindEvents(control_s, control_m, control_l);
		
		//get textsize from cookie
		if(jQuery.cookie("textsize") == "l"){ 
			control_l.addClass("active");
		}else if(jQuery.cookie("textsize") == "m"){ 
			control_m.addClass("active");
		}
		
		/* search for default setting - if not set, activate smallest text size */
		if(control_l.hasClass("active")){
		  control_l.click();
		}else if(control_m.hasClass("active")){
		  control_m.click();
		} else {
		  control_s.click();
		}
	},
	
	bindEvents: function(control_s, control_m, control_l){
		jQuery("#S24_textsize_s").click(function(){
			jQuery("body").removeClass("S24_textsize_m S24_textsize_l").addClass("S24_textsize_s");
			control_m.removeClass("active");
			control_l.removeClass("active");
			jQuery(this).addClass("active");
			jQuery.cookie("textsize", "s", {domain: "suomi24.fi", path: "/", expires: 7300});
		});
		jQuery("#S24_textsize_m").click(function(){
			jQuery("body").removeClass("S24_textsize_s S24_textsize_l").addClass("S24_textsize_m");
			control_s.removeClass("active");
			control_l.removeClass("active");
			jQuery(this).addClass("active");
			jQuery.cookie("textsize", "m", {domain: "suomi24.fi", path: "/", expires: 7300});
		});		
		jQuery("#S24_textsize_l").click(function(){
			jQuery("body").removeClass("S24_textsize_s S24_textsize_m").addClass("S24_textsize_l");
			control_m.removeClass("active");
			control_s.removeClass("active");
			jQuery(this).addClass("active");
			jQuery.cookie("textsize", "l", {domain: "suomi24.fi", path: "/", expires: 7300});
		});
	}
};

Suomi24.tori = { // tori box on the frontpage
  init : function(script_url) {
	  var container = jQuery("#S24_toribox div.S24_block_content");
	  this.bindEvents(container, script_url);
  },
  bindEvents: function(container, script_url){
	  var place = container.find("p.S24_place");
		var placeEdit = place.find("a");
		var placeSelect = container.find("#S24_placeSelector");
		var itemsCont = container.find("div.S24_tori_items");
		
		placeEdit.click(function(e){
			e.preventDefault();
			place.hide();
			placeSelect.show();
		});
		placeSelect.change(function(e){
			var loader = itemsCont.addLoadingImg();
			jQuery(this).hide();
			place.find("span").html(jQuery(this).find(":selected").html());
			place.show();
			
			jQuery.get(script_url+'?province='+jQuery(this).val(), function(data){
				// Edit DOM, update items!
				jQuery('#S24_toribox div.S24_tori_items').html(data);
				loader.remove();				
			});
		});
  }
};

Suomi24.uutiset = {
	countClick: function(domObj) {
		var obj = jQuery(domObj);
		var nid = obj.attr("data-nid");
		jQuery.get('/tools/crossnews/listmessage/'+nid+'/click_count');
	}
}

var weatherBoxInited = false;
Suomi24.weatherBox = {
		init: function(script_url, city) {
    if(!weatherBoxInited){
      jQuery.getScript("/sites/all/themes/s24default/js/jquery-autocomplete.js", function(){
        Suomi24.weatherBox.events(script_url);
      });
      
      jQuery.get(script_url + 'weather.php' + city, null, function(data){
        var res = jQuery.parseJSON(data);
        jQuery("#weatherResult").html(res.output);
        jQuery("#weatherInput").attr("value", res.cityname);
      });
      weatherBoxInited = true;
    }
	},

	
	events: function(script_url) {
		
		jQuery("#S24_saabox").find("form").submit(function(e){
			e.preventDefault();
		});
		
		function format(mail) {
			return mail.split(",")[1];
		}
		
    jQuery("#weatherInput").autocomplete(script_url+'autocomplete.php', {
      minChars: 2,
      dataType: "json",
      parse: function(data) {
        return jQuery.map(data, function(row) {
          return {
            data: row.id + ',' + row.name,
            value: row.id
          }
        });
      },
      formatItem: function(item) {
        return format(item);
      }
    }).result(function(e, item) {
      // when selected what happens
      jQuery.get(script_url + 'weather.php?place='+item.split(",")[0], null, function(data){
        var res = jQuery.parseJSON(data);
        jQuery("#weatherResult").html(res.output);
        jQuery("#weatherInput").attr("value", res.cityname);
      });
//      jQuery("#weatherInput").attr("value", item.split(",")[1]);
//      jQuery("#weatherResult").load(script_url+'weather.php?place='+item.split(",")[0]);
    });
  }
}

Suomi24.widgetTools =  {
		
	// Minimize / Maximize widget
	minmax: {
		init: function(tools) {
			var pack = tools.find("div.S24_widget_minmax span"); // get "buttons"
			if(pack.length == 0){ //abort if items don't exist
				return;
			}
			this.bindEvents(pack);
		},
		bindEvents: function(o) {
			o.each(function(){
				var parent = jQuery(this).closest("div.S24_widget");
				var content = parent.find("div.S24_block_content, div.S24_block_footer, div.S24_banner");
				jQuery(this).click(function(e){ // when a button is clicked
					e.preventDefault();
					item_id = parent.attr("data-id");
					
					var clicked = jQuery(this);
					var loader = parent.addLoadingImg();
										
					//slide out content if hidden
					if(content.is(":hidden")) {
						  loader.remove();
														
						  content.slideDown(animSpeed/2);
						  clicked.removeClass("minimized").attr("title", "Piilota");
						  						  
						  // if not logged in, show alert
						  /*logged = jQuery.parseJSON(data).logged;							  
						  if(!logged){
							parent.addBlockAlert(Suomi24.strings.settingsChangedAlert, true);
						  }*/
						
					// or hide if visible
					} else {
						  loader.remove();
							
						  content.slideUp(animSpeed/2);
						  clicked.addClass("minimized").attr("title", "Palauta");
						  
						  // if not logged in, show alert
						 /* logged = jQuery.parseJSON(data).logged;	
						  if(!logged){
							parent.addBlockAlert(Suomi24.strings.settingsChangedAlert, true);
						  }	*/
					}
					Suomi24.widgetTools.updateCookie(true);
				})
				if(jQuery(this).hasClass("minimized")){ // minimize elements that are supposed to be minimized by default
					content.hide();
					jQuery(this).addClass("minimized").attr("title", "Palauta");
				}
			});
		}
	},
	
	// Move
	move: {
		init: function(tools) {
			var pack = tools.find("div.S24_widget_move span"); // get "buttons"
			if(pack.length == 0){ //abort if items don't exist
				return;
			}
			this.bindEvents(pack);
		},
		bindEvents: function(o) {
			o.each(function(){
				var parent = jQuery(this).closest("div.S24_widget");
				var item_id = parent.attr("data-id");
				
				jQuery(this).click(function(e){ // when a button is clicked
					e.preventDefault();										
										
					var logged;
					
					var loader = parent.addLoadingImg();
					
					//move up
					if(jQuery(this).hasClass("S24_move_up") && !parent.hasClass(".S24_first")) {
							loader.remove();
														
							//move
							var prev = parent.prev("div.S24_widget");	
																	
							parent.fadeTo(0, 0).insertBefore(prev).fadeTo(animSpeed, 1);
							// update S24_first and S24_last
							if(prev.hasClass("S24_first")){
								prev.removeClass("S24_first");
								parent.addClass("S24_first");
							}
							if(parent.hasClass("S24_last")){
								parent.removeClass("S24_last");
								prev.addClass("S24_last");
							}
							
							// if not logged in, show alert
							 /* logged = jQuery.parseJSON(data).logged;	
								if(!logged){
								parent.addBlockAlert(Suomi24.strings.settingsChangedAlert, true);
								}	*/
							//});
				
					//move down
					} else if(jQuery(this).hasClass("S24_move_down") && !parent.hasClass(".S24_last")) {
							loader.remove();
														
							//move
							var next=parent.next("div.S24_widget");			
							parent.fadeTo(0, 0).insertAfter(next).fadeTo(animSpeed, 1);							
							
							// update S24_first and S24_last
							if(next.hasClass("S24_last")){
								next.removeClass("S24_last");
								parent.addClass("S24_last");
							}
							if(parent.hasClass("S24_first")){
								parent.removeClass("S24_first");
								next.addClass("S24_first");
							}
							
							// if not logged in, show alert
							 /* logged = jQuery.parseJSON(data).logged;	
								if(!logged){
								parent.addBlockAlert(Suomi24.strings.settingsChangedAlert, true);
								}	*/
							//});
					}
					Suomi24.widgetTools.updateCookie(true);
				});
			});
		}			
	},
	
	// Init all tools
	init: function(wrapper) {
		if(typeof(wrapper) == "undefined") {
			wrapper = jQuery("#S24_contentwrap");
		}
		//declare objects
		var widgets = jQuery("div.S24_widget", wrapper);
	    if(widgets.length == 0){ //abort if items don't exist
		  return;
		}
		var tools = jQuery();
				
		//hover fade effect and declaring objects (alpha png and opacity doesn't work on IE, so ignore the MS skit...
		widgets.each(function(){
		  var this_tools = jQuery(this).find("div.S24_widget_tools");
		  tools = tools.add(this_tools);
			if(!ie){
			  this_tools.fadeTo(0, 0.5);
			  jQuery(this).hover(
				function() {
				  this_tools.fadeTo(100, 1);
				},
				function(){
				  this_tools.fadeTo(100, 0.5);
			  });
			}
		});
		
		//init
		this.minmax.init(tools);
		this.move.init(tools);
	},
	
	//order blocks according to cookie
	orderBlocks: function(leftCont, rightCont) {
		// destroy wrong cookies
		jQuery.cookie('suomi24_frontpage_prefs', null, {domain: "www.suomi24.fi"});
		jQuery.cookie('suomi24_frontpage_prefs', null, {domain: "suomi24.fi"});
		
		leftBlocksDef = leftCont.find("div.S24_widget");
		rightBlocksDef = rightCont.find("div.S24_widget");
		
		var cookieRead = jQuery.cookie('suomi24_frontpage_prefs');
		
		//if cookie not set (or is not json), do it now
		if (cookieRead == null || cookieRead.substr(0,1) != "{") {
			Suomi24.widgetTools.updateCookie(false);
			jQuery("body").removeClass("frontpageLoading");
		}
		
		// if it is set, reorder stuff
		else{
			try{
				var cookie = jQuery.parseJSON(jQuery.cookie('suomi24_frontpage_prefs'));
			}catch(err){
				Suomi24.widgetTools.updateCookie(false);
				jQuery("body").removeClass("frontpageLoading");
				return;
			}
			var leftOrder = cookie.left_list;
			var rightOrder = cookie.right_list;
			
			var leftBlocks = Array();
			var rightBlocks = Array();
			
			leftBlocksDef.each(function(){
				leftBlocks[jQuery(this).attr("data-id")] = jQuery(this);
			});
			
			for(i in rightOrder){
				var id=rightOrder[i];
				var minimized = false;
				if(rightOrder[i].substring(0,1)=="-"){
					id=id.substring(1);
					minimized = true;
				}
				var curBlock = rightBlocksDef.filter("[data-id="+id+"]");
				if(curBlock.length > 0){
					if(minimized){
						curBlock.find(".S24_widget_minmax span").addClass("minimized");
						curBlock.find("div.S24_block_content, div.S24_block_footer, div.S24_banner").hide();
					}
					rightBlocks.push(curBlock);
				}
			}
			
			for(i in leftOrder.reverse()){ //going through in reverse order and prepend() to make sure banner doesn't come first
				if(!isNaN(leftOrder[i]) && leftOrder[i] != null){
					var curBlock = leftBlocks[Math.abs(leftOrder[i])]
				}
				
				if(curBlock.length>0){
					leftCont.prepend(curBlock);
					if(leftOrder[i] < 0){
						curBlock.find(".S24_widget_minmax span").addClass("minimized");
						curBlock.find("div.S24_block_content, div.S24_block_footer, div.S24_banner").hide();
					}else{
						curBlock.find(".S24_widget_minmax span").removeClass("minimized");
						curBlock.find("div.S24_block_content, div.S24_block_footer, div.S24_banner").show();
					}
				}
			}	
			
			for(i in rightBlocks.reverse()){
				rightCont.prepend(rightBlocks[i]);
			}	
		}
		
		leftCont.find("div.S24_widget").removeClass("S24_first S24_last");
		rightCont.find("div.S24_widget").removeClass("S24_first S24_last");
		leftCont.find("div.S24_widget:first").addClass("S24_first");
		rightCont.find("div.S24_widget:first").addClass("S24_first");
		leftCont.find("div.S24_widget:last").addClass("S24_last");
		rightCont.find("div.S24_widget:last").addClass("S24_last");

		//show things by removing body class
		jQuery("body").removeClass("frontpageLoading");
		
		Suomi24.widgetTools.updateCookie(false);
	},
	
	//update frontpage block cookie based on the current order of blocks (pass parameter true if initial set, with no changes made)
	updateCookie: function(updateDB) {
		
		var leftBlocks = jQuery("#S24_midcol div.S24_widget");
		var rightBlocks = jQuery("#S24_rightcol div.S24_widget");
		
		var time = new Date().getTime();
		time = Math.round(time/1000);
		
		var cookie = {"cookies_setted": time,"left_list":[], "right_list":[]};
		
		var leftArray = leftBlocks.each(function(){
			var id=jQuery(this).attr("data-id");
			if(jQuery(this).find(".S24_widget_minmax span").hasClass("minimized")){
				id = "-"+id
			}
			cookie.left_list.push(id)
		});
		var rightArray = rightBlocks.each(function(){
			var id=jQuery(this).attr("data-id");
			if(jQuery(this).find(".S24_widget_minmax span").hasClass("minimized")){
				id = "-"+id
			}
			cookie.right_list.push(id);
		});

		//let's make the string for the cookie (should be valid JSON)
		var cookString = "{\"cookies_setted\": "+time+",\"left_list\":[";
		for(var i in cookie.left_list){
			cookString += "\""+cookie.left_list[i]+"\"";
			if(i != cookie.left_list.length-1){
				cookString += ",";
			}
		}
		cookString += "], \"right_list\":[";
		for(var i in cookie.right_list){
			cookString += "\""+cookie.right_list[i]+"\"";
			if(i != cookie.right_list.length-1){
				cookString += ",";
			}
		}
		cookString += "]}";
		
		jQuery.cookie('suomi24_frontpage_prefs', cookString);
		
    if(updateDB){
      // write the stuff into db (the "/0/1/0" is a tail from ancient development, php cleanup needed)
      jQuery.get("/s24frontpage/writecookie/0/1/0", function(data) {});
    }
		return;	
	}
};

/**
* handles the Web Of Trust (wot) links
*/

Suomi24.wot = {
  domStatus: {},
  /**
  * helper that returns hostname from url
  */
  get_hostname: function(url) {
    var m = ((url||'')+'').match(/^http:\/\/[^/]+/);
    if(m){
      return m[0].substring(7);
    }
    var sec = ((url||'')+'').match(/^https:\/\/[^/]+/);
    if(sec){
      return sec[0].substring(8);
    }
    var sec = ((url||'')+'').match(/^ftp:\/\/[^/]+/);
    if(sec){
      return sec[0].substring(6);
    }
    return null;
  }, 
  /**
  * returns component based on i and val array
  */
  getComponent: function(i, val){
    var name = "";
    switch(i){
      case 0:
        name = Drupal.t("WOT Trustworthiness");
        break;
      case 1:
        name = Drupal.t("WOT Vendor reliability");
        break;
      case 2:
        name = Drupal.t("WOT Privacy");
        break;
      case 4:
        name = Drupal.t("WOT Child safety");
        break;
    }
    return {"name" : name, "reputation" : val[0], "confidence" : val[1] };
  },
  /*
  * return unknown
  */
  getUnknown: function(i){
    return Suomi24.wot.getComponent(i, new Array(-1,0));
  },
  /*
  *
  */
  getReputation: function (val){
    if(val >= 80){ return "excellent";
    } else if(val >= 60){ return "good";
    } else if(val >= 40){ return "unsatisfactory";
    } else if(val >= 20){ return "poor";
    } else if(val == -1){ return "unknown";
    } else { return "verypoor";
    }
  }, 
  /*
  *
  */
  getConfidence: function (val){
    if(val >= 45){ return "5";
    } else if(val >= 34){ return "4";
    } else if(val >= 23){ return "3";
    } else if(val >= 12){ return "2";
    } else if(val >= 6){ return "1";
    } else { return "0";
    }
  },
  init: function (){ 
		//Ajax load hoverIntent plugin
    jQuery.getScript("/sites/all/themes/s24default/js/jquery.hoverIntent.minified.js", function(){
      var domstocheck = new Array();
      var $links = jQuery("#S24_midcol div.content a:not(.wotDone)").filter(function(){
        return $(this).closest("span.wotCont").length == 0;
      });
      jQuery.each($links, function(i, val){
        $(this).addClass("wotDone");
        cDom = Suomi24.wot.get_hostname(val.href);
        if(cDom != null && jQuery.inArray(cDom, domstocheck) == -1 && cDom.indexOf(".suomi24.fi") == -1){
          domstocheck.push(cDom);
        }
      });
      if(domstocheck.length > 0){
        jQuery.getJSON("http://api.mywot.com/0.4/public_link_json?hosts="+domstocheck.join("/")+"/&callback=?",
        function(data) {
          jQuery.each(data, function(i,item){
            gen = 0;
            divider = 0; // 
            if(typeof(item[0]) != "undefined"){ // item has value
              com0 = Suomi24.wot.getComponent(0, item[0]);
              gen = gen + com0["reputation"];
              divider++;
            } else {
              com0 = Suomi24.wot.getUnknown(0);
            }
            if(typeof(item[1]) != "undefined"){ // item has value
              com1 = Suomi24.wot.getComponent(1, item[1]);
              gen = gen + com1["reputation"];
              divider++;
            } else {
              com1 = Suomi24.wot.getUnknown(1);
            }
            if(typeof(item[2]) != "undefined"){ // item has value
              com2 = Suomi24.wot.getComponent(2, item[2]);
              gen = gen + com2["reputation"];
              divider++;
            } else {
              com2 = Suomi24.wot.getUnknown(2);
            }            
            if(typeof(item[4]) != "undefined"){ // item has value
              com4 = Suomi24.wot.getComponent(4, item[4]);
              gen = gen + com4["reputation"];
              divider++;
            } else {
              com4 = Suomi24.wot.getUnknown(4);
            }
            
            if(divider == 0){
              gen = -1;
            } else {
              gen = gen / divider;
            }
            
            Suomi24.wot.domStatus[item.target] = {
                0 : com0,
                1 : com1,
                2 : com2,
                4 : com4,
                "gen" : gen
            };
            if(item.target.substring(4) != "www."){
              Suomi24.wot.domStatus["www."+item.target] = {
                0 : com0,
                1 : com1,
                2 : com2,
                4 : com4,
                "gen" : gen
              };
            }
          });
          // go through the links again
          jQuery.each($links, function(i, val){
            cDom = Suomi24.wot.get_hostname(val.href);
            if(Suomi24.wot.domStatus[cDom] != null){
              var rating = Suomi24.wot.getReputation(Suomi24.wot.domStatus[cDom]["gen"]);
              if(rating == "verypoor" || rating == "poor"){
                val.href = '/wot/' + val.href;
              } 
              // create random number to be used as wot div id
              var useid = (i+1) * 25;
              newSpan = $('<span class="wotCont"><a href="http://www.mywot.com/scorecard/'+cDom+'" onClick="_gaq.push([\'_trackEvent\', \'Outbound\', \'WOT\', \'PopupScorecard\']);" target="_blank" ><img src="http://suomi24-static.fi/b/img/wot/'+rating+'.png" alt="" class="wotImg" /></a>'+
    '<div class="wot" id="wot'+useid+'"><a href="http://www.mywot.com/scorecard/'+cDom+'" onClick="_gaq.push([\'_trackEvent\', \'Outbound\', \'WOT\', \'PopupScorecard\']);" target="_blank" class="wot-link"><img src="http://suomi24-static.fi/b/img/wot/wot_wide_160.gif" width="160" height="21" alt="Web of Trust" /><br />'+
      Suomi24.wot.domStatus[cDom][0]["name"]+'<br />'+
      '<img src="http://suomi24-static.fi/b/img/wot/'+Suomi24.wot.getReputation(Suomi24.wot.domStatus[cDom][0]["reputation"])+'.png" alt="" /><img src="http://suomi24-static.fi/b/img/wot/c_'+Suomi24.wot.getConfidence(Suomi24.wot.domStatus[cDom][0]["confidence"])+'.png" border="0" alt="" /><br />'+
      Suomi24.wot.domStatus[cDom][1]["name"]+'<br />'+
      '<img src="http://suomi24-static.fi/b/img/wot/'+Suomi24.wot.getReputation(Suomi24.wot.domStatus[cDom][1]["reputation"])+'.png" alt="" /><img src="http://suomi24-static.fi/b/img/wot/c_'+Suomi24.wot.getConfidence(Suomi24.wot.domStatus[cDom][1]["confidence"])+'.png" border="0" alt="" /><br />'+
      Suomi24.wot.domStatus[cDom][2]["name"]+'<br />'+
      '<img src="http://suomi24-static.fi/b/img/wot/'+Suomi24.wot.getReputation(Suomi24.wot.domStatus[cDom][2]["reputation"])+'.png" alt="" /><img src="http://suomi24-static.fi/b/img/wot/c_'+Suomi24.wot.getConfidence(Suomi24.wot.domStatus[cDom][2]["confidence"])+'.png" border="0" alt="" /><br />'+
      Suomi24.wot.domStatus[cDom][4]["name"]+'<br />'+
      '<img src="http://suomi24-static.fi/b/img/wot/'+Suomi24.wot.getReputation(Suomi24.wot.domStatus[cDom][4]["reputation"])+'.png" alt="" /><img src="http://suomi24-static.fi/b/img/wot/c_'+Suomi24.wot.getConfidence(Suomi24.wot.domStatus[cDom][4]["confidence"])+'.png" border="0" alt="" /><br /></a>'+
    '<div class="horizontal-line"></div><a href=" http://www.mywot.com/download.php?src=s24" onClick="_gaq.push([\'_trackEvent\', \'Outbound\', \'WOT\', \'PopupDownload\']);" target="_blank">'+Drupal.t("Install WOT extension")+'</a></div></span>');
							// zIndex hack for IE7
              newSpan.hoverIntent(function(){ 
                  jQuery('#wot'+useid).fadeIn(animSpeed/2).css({zIndex: 1000});
                }, function(){
                  jQuery('#wot'+useid).fadeOut(animSpeed/2, function(){
                    jQuery(this).css({zIndex: 0});
                  });
              });
              jQuery(val).after(newSpan);
            }
          });
        });
      }
    });
  }
};

jQuery(document).ready(function() {  
  //Styling some elements
  jQuery("table.S24_odds_evens tr:even").addClass("even");
  jQuery("body.S24_forum-category #S24_thread_top10 .S24_category_top10_rest li:odd").css("border", "none");
  Suomi24.ajaxBubble.init();
	Suomi24.mina.vcard.init();
	Suomi24.mina.vcard_new.init();
	
	// init profanity filter
	if(jQuery("body").hasClass("S24_profanity")){
		Suomi24.profanity.init();
	}	else if(jQuery("body").is(".page-debate, .node-type-forum")){ // if no profanity on page, just show the on/off switch in the tools area
		Suomi24.profanity.bindToolbox();
	}			
});


/** METHODS **/

/** Add a closeable .S24_block_intro
  params: 
    text = content of the block
	deleteOthers = true -> delete all other block alerts  **/
var currentBlockAlert = jQuery(); // for performance, we need to memorize which is the currently open alert
jQuery.fn.addBlockAlert = function(text, deleteOthers){	
	var alertDiv;
	
	// if there already is an alert, delete it so there won't be two of them!
	var existing = this.find(".S24_block_alert");
	if(existing.length > 0) {
		existing.fadeOut(animSpeed/4).remove();
	} 
	
	if(deleteOthers){
	  // delete all other alerts on the page	
	  currentBlockAlert.fadeOut(animSpeed/4).remove();
	}
	
	alertDiv = jQuery('<div class="S24_block_alert">'+text+'</div>');
	
	var blockContent = this.find(".S24_block_content");
	var closeBtn = jQuery('<span class="S24_close" title="Sulje"></span>');
	alertDiv.append(closeBtn);
		
	if(blockContent.length == 0){
		// if block structure is simple (no block_content), just put the alert in the beginning
		this.prepend(alertDiv);
	} else {
		// else insert between header and content
		alertDiv.insertBefore(blockContent);
	}
	
	closeBtn.click(function(e){
		e.preventDefault;
		alertDiv.fadeOut(animSpeed/4);
	});
	
	currentBlockAlert = alertDiv;
	
	return this;
}

/** Add loading animation to an element (adds loading animation in the center of the element
params: bool fade =  whether to add a semi-transparent overlay (defaults true)
**/
jQuery.fn.addLoadingImg = function(fade){
	var loader = jQuery('<div class="loading"></div>');
	if (fade != false) { // wrap loader in 
		loader.addClass("overlay");
	}
	var pos=this.offset();
	
	var padLeft = 0;
	if (!isNaN(parseInt(this.css("padding-left")))){
		padLeft = parseInt(this.css("padding-left"));
	}
	var padRight = 0;
	if (!isNaN(parseInt(this.css("padding-right")))){
		padRight = parseInt(this.css("padding-right"));
	}
	var borLeft = 0;
	if (!isNaN(parseInt(this.css("border-left-width")))){
		borLeft = parseInt(this.css("border-left-width"));
	}
	var borRight = 0;
	if (!isNaN(parseInt(this.css("border-right-width")))){
		borRight = parseInt(this.css("border-right-width"));
	}
	var padTop = 0;
	if (!isNaN(parseInt(this.css("padding-top")))){
		padTop = parseInt(this.css("padding-top"));
	}
	var padBottom = 0;
	if (!isNaN(parseInt(this.css("padding-bottom")))){
		padBottom = parseInt(this.css("padding-bottom"));
	}
	var borTop = 0;
	if (!isNaN(parseInt(this.css("border-top-width")))){
		borTop = parseInt(this.css("border-top-width"));
	}
	var borBottom = 0;
	if (!isNaN(parseInt(this.css("border-bottom-width")))){
		borBottom = parseInt(this.css("border-bottom-width"));
	}
	var elemWidth = this.width()+padLeft+padRight+borLeft+borRight;
	var elemHeight = this.height()+padTop+padBottom+borTop+borBottom;
	
	loader.css({
		width: elemWidth,
		height: elemHeight,
		top: pos.top,
		left: pos.left
	});
	
	jQuery("body").append(loader);
	loader.fadeTo(0, 0).fadeTo(animSpeed/4, 0.7)
		
	return loader;
}

$.extend({
    parseJSON: function( data ) {
        if ( typeof data !== "string" || !data ) {
            return null;
        }    
        data = jQuery.trim( data );    
        if ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
            .replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
            .replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {    
            return window.JSON && window.JSON.parse ?
                window.JSON.parse( data ) :
                (new Function("return " + data))();    
        } else {
            jQuery.error( "Invalid JSON: " + data );
        }
    }
});

// function to find the location of the cursor in textareas
$.fn.caretPos = function() {
  el = $(this);

  var h = 0, w = 0;

  var div = document.createElement('div');
  document.body.appendChild(div);
  $(div).css({
   position: 'absolute',
   left: -1000,
   top: -1000,
   display: 'none',
   whiteSpace: 'pre-wrap'
  });
  
  if($(el).html().length == 0){
    $(div).html($(el).val());
  }else{
    $(div).html($(el).html());
  }
  
  var styles = ['font-size','font-style', 'font-weight', 'font-family','line-height', 'text-transform', 'letter-spacing'];
  $(styles).each(function() {
   var s = this.toString();
   $(div).css(s, $(el).css(s));
  });
  
  $(div).css({maxHeight: el.height()});
  $(div).css({maxWidth: el.width()});
  
  var lines = $(div).html().split("\n");
  lastLine = lines[lines.length-1];
  if(lastLine.length == 0){ // if last line is empty, we need to add a foo character to make it count
    $(div).html($(div).html()+"l");
  }
  
  h = $(div).outerHeight();
  
  $(div).html(lastLine);
  
  if($(div).outerWidth() == el.width()) {
    w = 0;
  }else{
    w = $(div).outerWidth();
  }

  //$(div).remove();

  var ret = {
   height: h,
   width: w
  };

  return ret;
 }

// Collapse comments
function hideShowComment(cid){
	var target = jQuery("#comment-"+cid);
	
	target.toggleClass("collapsed");

	//fix ugly bug where IE forgets to move elements
	if(ie7){
		var tempEl = target.next(".indented, .comment").find(".S24_post_infoWrap:first").hide();
		tempEl.show();
	}
}


/* FOR DEBUGGING
jQuery(document).ajaxError(function(event, request, settings){  
	//console.log("Ajax error in url: " + settings.url);
}); */


//turn object into a query string (used in emediate ad targeting)
Object.toQueryString = function(source){
  var queryString = [];
  for (var property in source) queryString.push(property + '=' + source[property]);
  return queryString.join(arguments[1] || '&');
}
