jQuery.noConflict();
var $j = jQuery;

jQuery.fn.fadeToggle = function(speed, easing, callback) {
    return this.animate({
        opacity: 'toggle'
    }, speed, easing, callback);
};

jQuery.fn.randomize = function(childElem) {
    return this.each(function() {
        var $this = jQuery(this);
        var elems = $this.children(childElem);
        elems.sort(function() {
            return (Math.round(Math.random())-0.5);
        });
        $this.empty();
        for(var i=0; i < elems.length; i++)
            $this.append(elems[i]);

    });
}

//Andrei: added on 04/02/10 s:speed(ms); o:desired opacity level
jQuery.fn.fadingButton = function(s,o) {
    return this.each(function(i) {
        jQuery(this).hover(function(){
            jQuery(this).stop().fadeTo(s,o)
        },function(){
            jQuery(this).stop().fadeTo(s,1)
        })
    })
};

jQuery.fn.fadingSiblings = function() {
    return this.each(function(i) {
        $j(this).children().hover(function () {
            $j(this).siblings().filter(":visible").stop().fadeTo(800, 0.4);
        },
        function () {
            $j(this).siblings().filter(":visible").stop().fadeTo(700, 1);
        });

    })
};

jQuery.fn.twitterLinks = function() {
    var twitterMethods = {
        linkUrl : function(s) {
            var regexp = /((ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?)/gi ;
            var result = s.replace(regexp,"<a href=\"$1\">$1</a>")
            return result;
        },
        linkUser : function(s) {
            var regexp = /[\@]+([A-Za-z0-9-_]+)/gi ;
            var result = s.replace(regexp,"<a href=\"http://twitter.com/$1\">@$1</a>")
            return result;
        },
        linkHash : function(s) {
            var regexp = / [\#]+([A-Za-z0-9-_]+)/gi ;
            var result = s.replace(regexp, ' <a href="http://search.twitter.com/search?q=&tag=$1&lang=all">#$1</a>')
            return result;
        }
    }
    return this.each(function(i) {
        var $origHTML = $j(this).html();
        var newHTML = twitterMethods.linkUrl($origHTML);
        newHTML = twitterMethods.linkUser(newHTML);
        newHTML = twitterMethods.linkHash(newHTML);
        $j(this).html(newHTML);
    })
};

jQuery.fn.getIndex = function(){
    var $p=jQuery(this).parent().children();
    return $p.index(this);
};
jQuery.fn.vAlign = function() {
    return this.each(function(i){
        jQuery(this).children().wrapAll('<div class="nitinh-vAlign" style="position:relative;"></div>');
        var div = jQuery(this).children('div.nitinh-vAlign');
        var ph = jQuery(this).innerHeight();
        var dh = div.height();
        var mh = (ph - dh) / 2;
        div.css('top', mh);
    });
};
jQuery.fn.ZissouTweets = function(opts){
    return this.each(function() {
        var defaults = {
            timeout       : 2000,   //timeout before switching to the next tweet
            movingSpeed   : 500,    //speed of moving tweets up
            opacitySpeed  : 500,    //speed of fading out upper tweet
            height        : 150,    //height of tweeter container
            pause         : 1,      //true or false (pause on hover)
            formatLinks   : 1       //whether or not use link formatting for hash signs, @usernames, and regular URLs
        }
        var o = jQuery.extend(defaults, opts);
        var $cont = $j(this);
        var cont = $cont[0];
        if (o.formatLinks) $cont.find("div.tweet").twitterLinks();
        if (o.pause)
	   $cont.hover(function(){cont.twitterSearchPause = true;},function(){cont.twitterSearchPause = false;});

        $cont.css({'height':o.height})
        function go() {
            if (cont.twitterSearchPause) {
                setTimeout(go, 500);
                return;
	    }
            var $el = $cont.children(':first')
            $el.animate({ opacity: 0 }, o.opacitySpeed, function() {
                var h = $el.outerHeight();
                $el.animate({marginTop: -h}, o.movingSpeed, function() {
                    $el.css({marginTop: 0,	opacity: 1});
                    $el.show().appendTo($cont);
                });
                setTimeout(go, o.timeout);
            });
        }
        setTimeout(go, o.timeout);
    })
};
jQuery.expr[':'].external = function(obj){
    return !obj.href.match(/^mailto\:/)
    && (obj.hostname != location.hostname)
    && obj.href.match(/\S/)                   // Andrei: added on 03/31 to filter only non-empty links
    && !obj.href.match(/^http\:\/\/www.addthis.com\//)
    && !obj.href.match(/^libertysecure.net\//) // Andrei: added on 03/31 to filter secure zone URLs
    && !location.href.match(/^libertysecure.net\//) //Andrei: switch off selector if on secure page
    && !obj.href.match(/^javascript\:/);
};


var addthis_pub="libertyconcepts";

if (typeof(TopUp) != "undefined") {
    TopUp.host = "https://libjs.s3.amazonaws.com/";
    TopUp.images_path = "JS/topup/images/";
    var flickrAreaOpts = {
        title: "{alt} ({current} of {total})",
        group: "flickr",
        readAltText: 1,
        shaded: 1,
        overlayClose: 1,
        modal: 1
    }
    TopUp.addPresets({
        "#flickrFeed li a" : flickrAreaOpts
    })
}

var plugins = {
    blogComments : function(admin){
        admin = (admin == null) ? "Administrative User" : admin;
        jQuery("div.comment:odd").addClass("commentOdd");
        jQuery("div.comment:even").addClass("commentEven");
        jQuery("p.postedBy:contains("+admin+")").parent().addClass("administrator");
        jQuery("#blog-comments input:submit").button();
    },
    flickrFeed : function(o){
        var retriveMethod,
        retriveEntityType,
        retriveEntityValue,
        photolength;
        var defaults = {
            cont: "#flickr",
            api: "eb4be2bc9b39e0625af47006c9a790cc",
            type: "set",
            set: "72157622255407423",
            userId : "",
            num: 9,
            limit: 15
        }
        $j.extend(defaults, o);

        if ($j(defaults.cont).length) {
            if (defaults.type == 'set') {
                retriveMethod = "flickr.photosets.getPhotos";
                retriveEntityType = "photoset_id";
                retriveEntityValue = defaults.set
            }
            else {
                retriveMethod = "flickr.people.getPublicPhotos";
                retriveEntityType = "user_id";
                retriveEntityValue = defaults.userId;
            }
            $j(defaults.cont).append("<ul id='flickrFeed' class='flickrFeed'/>");
            $j.getJSON('http://api.flickr.com/services/rest/?format=json&jsoncallback=?&per_page=' + defaults.limit + '&api_key=' + defaults.api + '&method='+retriveMethod+'&'+retriveEntityType+'=' + retriveEntityValue, function (Data) {
                if (Data.stat == "ok") {
                    if (defaults.type == 'set') {
                        photolength = Data.photoset.photo.length
                    }
                    else {
                        photolength = Data.photos.photo.length
                    }
                    for (var i = 0; i < photolength; i++) {
                        var photo = (defaults.type == 'set') ? Data.photoset.photo[i] : Data.photos.photo[i];
                        var Thum = 'http://farm' + photo['farm'] + '.static.flickr.com/' + photo['server'] + '/' + photo['id'] + '_' + photo['secret'] + '_' + 's.jpg';
                        $j("#flickrFeed").append('<li style="height:75px; width:75px; background:url(http://d8ldk29pm7a3h.cloudfront.net/images/preloaders/89.gif) no-repeat center center #fff" id="photo'+ i +'"><a rel="flickrFeedColorbox" href="' + Thum.replace('_s.jpg', '.jpg') + '" title="' + photo['title'] + '"><img src="' + Thum + '" /></a></li>');
                    }
                    $j("ul#flickrFeed").randomize();
                    $j("ul#flickrFeed li:eq("+ defaults.num +")").css({
                        "margin-right":0
                    }).nextAll().hide().addClass('hiddenPhoto');
                    $j('ul.flickrFeed').children().hover(function () {
                        $j(this).siblings().not('.hiddenPhoto').stop().fadeTo(500, 0.4);
                    },
                    function () {
                        $j(this).siblings().not('.hiddenPhoto').stop().fadeTo(500, 1);
                    });
                    $j(defaults.cont +" a").removeClass("external");
                    if ($j.isFunction($j.fn.colorbox)) {
                        $j(defaults.cont+" a[rel='flickrFeedColorbox']").colorbox();
                    }
                    $j("ul#flickrFeed").addClass("group")
                }
            })
        }

    },
    externalLinks : function(){
        $j('a:external').addClass('external');
        $j('a.external').click(function() {
            var link = $j(this).attr('href');
            window.open(link);
            return false;
        });
    },
    pageTools : {
        init : function(elt) {
            $j("#font_select").click(function(){
                plugins.pageTools.animateContentFontSize(elt,12)
            });
            $j("#font_select_med").click(function(){
                plugins.pageTools.animateContentFontSize(elt,15)
            });
            $j("#font_select_large").click(function(){
                plugins.pageTools.animateContentFontSize(elt,20)
            });
        },
        animateContentFontSize : function(elt,s){
            $j(elt).stop().animate({
                fontSize: s+"px"
                }, 300 )
        }
    }

}
