
var globalsearch = true;
(function($) {

var API_CLIENT_ID = "ytapi-Olivialehti-Olivialehti-ekg340q4-0";
var API_DEVELOPER_KEY = "AI39si6vD5ebE-M4U-Qi0pPYAeQ17j4S1OxYIIzWvPUielCa52itKsAOo-NlnqFuUCt0kb1gfIf2uhcGbPrGlYWzx8Tm6AAsFA";

function getVideoInfo(videoId, callback) {
    if(globalsearch) {
        var url = "http://gdata.youtube.com/feeds/api/videos?v=2&format=5&alt=json-in-script&callback=?";
        url += "&client=" + API_CLIENT_ID + "&key=" + API_DEVELOPER_KEY;
        url += "&q=" + videoId;
    } else {
        url = "http://gdata.youtube.com/feeds/api/users/Olivialehti/uploads?v=2&alt=json-in-script&callback=?";
        url += "&client=" + API_CLIENT_ID + "&key=" + API_DEVELOPER_KEY;

    }
    var foo = videoId;

    $.getJSON(url, function(data) {
        if (data.feed && data.feed.entry && data.feed.entry.length > 0) {
            for (foobar=0; foobar<=(data.feed.entry.length - 1); foobar++)
            {
                var v = data.feed.entry[foobar];
                
                if (v.id.$t.search(foo) >= 0) {
                    var dura = 0;
                    if (v.media$group && v.media$group.yt$duration)
                    
                        dura = parseInt(v.media$group.yt$duration.seconds, 10);
                    
                    var min = Math.floor(dura / 60), sec = dura % 60;
                    if (sec < 10) sec = "0" + sec;
                    
                    var ratingMin = 0, ratingMax = 0, rating = 0, numRaters = 0, viewCount = 0, authorName = "", authorLink = "";
                    
                    if (v.gd$rating) {
                        ratingMin = parseFloat(v.gd$rating.min);
                        ratingMax = parseFloat(v.gd$rating.max);
                        rating = (parseFloat(v.gd$rating.average) - ratingMin) / (ratingMax - ratingMin);
                        numRaters = parseInt(v.gd$rating.numRaters, 10);
                    }
                    
                    if (v.yt$statistics)
                        viewCount = parseInt(v.yt$statistics.viewCount);
                    
                    if (v.author && v.author.length > 0 && v.author[0].name && v.author[0].uri)
                    {
                        authorName = v.author[0].name.$t;
                        authorLink = v.author[0].uri.$t;
                    }
                    
                    var info = {title: v.title.$t, duration: min + ":" + sec,
                        authorName: authorName, authorLink: authorLink,
                        rating: rating, numRaters: numRaters, viewCount: viewCount,
                        src: v.content.src};
                    callback(info);
                }
            }
        } else {
            window.status = "Error fetching video information";
        }
    });
}

jQuery.fn.tinyrating = function(info) {
    var width = Math.ceil(12 * 4 * info.rating);
    var fillWidth = 12 * 5 - width;
    
    jQuery.each(this, function() {
        $(this).find(".tinyrating span:first").css("paddingLeft", width + "px").end()
            .find(".tinyrating span.fill").css("paddingLeft", fillWidth + "px").end()
            .find(".numraters").text(info.numRaters);
    });
};

jQuery.fn.cloudvideo = function(videoId, showVideo) {
    jQuery.each(this, function() {
        var root = $(this);
        
        getVideoInfo(videoId, function(info) {
            $(".videotitle:empty", root).text(info.title);
            $(".videoduration", root).text(info.duration);
            $(".videoauthor", root).text(info.authorName).attr("href", info.authorLink);
            $(".tinyrating", root).tinyrating(info);
            $(".videoviewcount", root).text(info.viewCount);
            
            if (showVideo) {
                var id = $(".video", root).attr("id");
                var params = {allowScriptAccess: "always"};
                swfobject.embedSWF(info.src, id, "571", "343", "8", null, null, params);
            }
        });
    });
};

jQuery.fn.videoliftup = function(videoId) {
    jQuery.each(this, function() {
        var root = $(this);
        
        getVideoInfo(videoId, function(info) {
            $(".videotitle:empty", root).text(info.title);
            $(".videoduration", root).text(info.duration);
            $(".videorating", root).tinyrating(info);
            $(".videoviewcount", root).text(info.viewCount);
        });
    });
};

jQuery.fn.zoomable = function() {
    var zoomImage = $("<img src=\"\" />");
    zoomImage.css({display: "none", position: "absolute", zIndex: 50, height: 235});
    $("body").append(zoomImage);
    zoomImage.bind("mouseleave", function() {
        zoomImage.css({display: "none"});
    }).click(function() {
        if (this._href)
            location.href = this._href;
    });
    
    jQuery.each(this, function() {
        var el = $(this);
        var href = el.parents("a").attr("href");
        
        el.bind("mouseenter", function() {
            var pos = el.offset();
            var x = Math.floor(pos.left - el.width() * (zoomImage.height() / el.height() - 1) * 0.5);
            zoomImage.attr("src", el.attr("src"));
            zoomImage.css({top: (pos.top - 40) + "px", left: x + "px", display: "block"});
            zoomImage[0]._href = href;
            
            if (href)
                zoomImage.css({cursor: "pointer"});
            else
                zoomImage.css({cursor: ""});
        });
    });
};

window.init_header = function() {
    var menuHideTimer = null;

    $("#headerbar,#menubar").bind("mouseenter", function() {
        $("#menubar").css({display: "block"});
		$("#topflash").css({visibility: "hidden"});
		//$(".tall-banner").css({visibility: "hidden"});
        if (menuHideTimer) {
            clearTimeout(menuHideTimer);
            menuHideTimer = null;
        }
    }).bind("mouseleave", function() {
        if (!menuHideTimer) {
            menuHideTimer = setTimeout(function() {
                $("#menubar").css({display: "none"});
				$("#topflash").css({visibility: "visible"});
				//$(".tall-banner").css({visibility: "visible"});
            }, 200);
        }
    });
	
	$("div.mainnav ul.Menu-l0>li").hover(function() {
		$(">a", this).addClass("hover");
	}, function() {
		$(">a", this).removeClass("hover");
	});
    
    function doSearch(e) {
        var terms = $("#minisearchinput").val().replace(/^\s+|\s+$/g, "");
        if (terms != "") {
            location.href = "/SearchResults/tabid/39/Default.aspx?Search=" + encodeURIComponent(terms);
        }
        e.preventDefault();
        return false;
    }
    
    $("#minisearchinput").click(function() {
        this.select();
    }).keypress(function(e) {
        if (e.which == 13) {
            return doSearch(e);
        }
    });
    
    $("#minisearchbutton").click(doSearch);
};

jQuery.init_popup = function() {
    var popupHideTimer = null;
	$("#miniPopup li .pops").bind("mouseenter", function() {
		//var el = $(this).parent().parent().find(".popInfo");
		var el = $(this).parent().parent();
		//$("#miniPopup li .popInfo").css({display: "none"});
		$("#miniPopup li").attr({className: ""});
		el.attr({className: "popHover"});
		$(".tall-banner").css({visibility: "hidden"});
        //el.css({display: "block"});
		
        if (popupHideTimer) {
            clearTimeout(popupHideTimer);
            popupHideTimer = null;
        }
    }).bind("mouseleave", function() {
	//var el = $(this).parent().parent().find(".popInfo");
	var el = $(this).parent().parent();
        if (!popupHideTimer) {
            popupHideTimer = setTimeout(function() {
                //el.css({display: "none"});
                el.attr({className: ""});
				$(".tall-banner").css({visibility: "visible"});
            },200);
        };
	});	
	$("#miniPopup li .popInfo").bind("mouseenter", function() {
        //$(this).css({display: "block"});
        $(this).parent().attr({className: "popHover"});
        if (popupHideTimer) {
            clearTimeout(popupHideTimer);
            popupHideTimer = null;
        }
    }).bind("mouseleave", function() {
		//el = $(this);
		el = $(this).parent();
        if (!popupHideTimer) {
            popupHideTimer = setTimeout(function() {
                //el.css({display: "none"});
                el.attr({className: ""});
				$(".tall-banner").css({visibility: "visible"});
            },500);
        }
    });
	
};

window.doPost = function(name, value) {
    var input = $("<input type=\"hidden\" />");
    input.attr("name", name).val(value);
    $("#Form").append(input).submit();
    return false;
};

window.serverFBMLLoaded = function() {
    jQuery('.serverfmbl-wait').hide();
};

window.addPrintStyles = function() {
    var link = $("<link rel=\"stylesheet\" type=\"text/css\" href=\"/Portals/0/Skins/olivia/print.css\" />");
    if (location.href && location.href.match(/[&?]PrintPreview\b/))
        $("body").prepend($("<a href=\"#\" class=\"printbutton\">Tulosta</a>").click(function() { window.print(); }));
    else
        link.attr("media", "print");
    $("head").append(link);
};

window.openPrintPreview = function() {
    var url = location.href;
    url += ((url.indexOf("?") == -1) ? "?" : "&") + "PrintPreview";
    window.open(url, "printpreview", "width=920,height=600,resizable=1,toolbar=1,menubar=1,scrollbars=1,status=0");
    return false;
};

window.showIfFacebookUser = function(e) {
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(function() {
            jQuery(e).show();
        }, function() { });
    });
};

window.ifFacebookUser = function(yes, no) {
    FB.ensureInit(function() {
        FB.Connect.ifUserConnected(yes, no || function() { });
    });
};

window.facebookInvite = function() {
    FB.IFrameUtil.CanvasUtilServer.run(true);
    
    var div = document.createElement("div");
    div.setAttribute("iframeWidth", "630px");
    div.setAttribute("iframeHeight", "560px");
    
    var dialog = new FB.UI.PopupDialog("Kutsu Facebook-kaverisi Oliviaan", div, false, false);
    dialog.setContentWidth(630);
    dialog.setContentHeight(560);
    dialog.set_placement(FB.UI.PopupPlacement.center);
    
    div.setAttribute("fbml", "<fb:fbml>"
      + "<fb:request-form style=\"width: 630px; height: 560px;\" action=\"" + document.location.href + "\" method=\"POST\" invite=\"false\" type=\"Olivialehti\""
      + "content=\"Haluaisin sinun tutustuvan olivialehti.fi -sivustoon <fb:req-choice url='http://www.olivialehti.fi/' label='Siirry Olivia-lehden sivustolle' />\">"
      + "<fb:multi-friend-selector showborder=\"false\" actiontext=\"Kutsu kaverisi Olivian nettisivuille\" rows=\"5\" bypass=\"cancel\" showborder=\"false\" />"
      + "</fb:request-form>"
      + "</fb:fbml>");
      
    dialog.show();
    
    FB_RequireFeatures(["XFBML"],function(){
        var fbml = new FB.XFBML.ServerFbml(div);
        FB.XFBML.Host.addElement(fbml);
    });
    
    return false;
};

$.Banner = function(zoneId) {
  
    var zoneId = zoneId;
    if(!zoneId) return false;

    var m3_u = (location.protocol=='https:'?'https://populus.relevant.fi/ajs.php':'http://populus.relevant.fi/ajs.php');
    var m3_r = Math.floor(Math.random()*99999999999);
    if (!document.MAX_used) document.MAX_used = ',';
    document.write ("<scr"+"ipt type='text/javascript' src='"+m3_u);
    document.write ("?zoneid="+zoneId);
    document.write ('&amp;cb=' + m3_r);
    if (document.MAX_used != ',') document.write ("&amp;exclude=" + document.MAX_used);
    document.write (document.charset ? '&amp;charset='+document.charset : (document.characterSet ? '&amp;charset='+document.characterSet : ''));
    document.write ("&amp;loc=" + escape(window.location));
    if (document.referrer) document.write ("&amp;referer=" + escape(document.referrer));
    if (document.context) document.write ("&context=" + escape(document.context));
    if (document.mmm_fo) document.write ("&amp;mmm_fo=1");
    document.write ("'><\/scr"+"ipt>");
    /*setTimeout("document.close();", 0);*/
};

})(jQuery);

var addthis_options = "facebook, delicious, digg, more";
var addthis_brand = "Olivia";
var addthis_header_color = "#000000";
var addthis_header_background = "#E8E8E8";
var addthis_language = "fi";
var addthis_localize = {
    share_caption: "Jaa tämä juttu",
    email_caption: "Lähetä sähköpostina",
    email: "Sähköposti",
    favorites: "Kirjanmerkit", 
    more: "muu..."}; 
