var $ = jQuery.noConflict();

//Center profile and company logos
jQuery(document).ready(function($){
	$(".avatar_large img, #channel_spon a img, body#events #bulk .g2 img").center({ horizontal: false  });
});


// jQuery :regex filter
// usage: $("p:regex('[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}')")
// http://blog.mastykarz.nl/jquery-regex-filter/

jQuery.extend(
    jQuery.expr[':'], {
        regex: function(a, i, m, r) {
            var r = new RegExp(m[3], 'i');
            return r.test(jQuery(a).text());
        }
    }
);

function getElement(id)
{
    if(document.all)
    {
        return document.all[id];
    }
    else if(document.getElementById)
    {
        return document.getElementById(id);
    }
    else
    {
        for(iLayer = 1; iLayer < document.layers.length; iLayer++)
        {
            if(document.layers[iLayer].id == id)
            {
                return document.layers[iLayer];
            }
        }
    }
    return null;
}

/**
    * Hide or show a block level element
    */
function toggleVisible(id)
{
    var obj = getElement(id);
    if(obj.style.display == "block")
    {
        obj.style.display = "none";
    }
    else if(obj.style.display == "none")
    {
        obj.style.display = "block";
    }
    else
    {
        obj.style.display = "block";
    }
} 

function showFade(id,focus)
{
    var obj = $("#"+id);
    obj.animate( { opacity: "show" }, 200, function() {
        if ( focus ) $("#"+focus).focus();
    } );
}


function hideFade(id,focus)
{
    var obj = $("#"+id);
    obj.animate( { opacity: "hide" }, 200, function() {
        if ( focus ) $("#"+focus).focus();
    } );
}

function toggleVisibleSlide(id,focus)
{
    var obj = $("#"+id);
    if ( obj[0].style.display == "none" )
    {
        showVisibleSlide(id,focus);
    }
    else
    {
        hideVisibleSlide(id,focus);
    }
}

//Open in external windows using a rel="external" attribute
function externalLinks() {
    if (!document.getElementsByTagName) return;
    var anchors = document.getElementsByTagName("a");
    for (var i=0; i<anchors.length; i++) {
        var anchor = anchors[i];
        if (anchor.getAttribute("href") && anchor.getAttribute("rel") == "external")
            anchor.target = "_blank";
    }
}

window.onload = externalLinks;

//Pre and ap ends
jQuery(document).ready(function($){
    $("#quote .relative")
        .prepend('<span></span>');
});

//Tab toggles
jQuery(document).ready(function($){ 
    $('#tabvanilla').tabs({ fx: { opacity: 'toggle' } });
});

//Post images max size
jQuery(document).ready(function($){ 
    //Configuration Options
    var max_width = 530;    //Sets the max width, in pixels, for every image
    var selector = '.single .full img'; //Sets the syntax for finding the images.  Defaults to all images.
    $(selector).each(function(){
        var width = $(this).width();
        var height = $(this).height();
        if (width > max_width) {
            //Set variables for manipulation
            var ratio = (height / width );
            var new_width = max_width;
            var new_height = (new_width * ratio);

            //Shrink the image and add link to full-sized image
            $(this).height(new_height).width(new_width);
            $(this).hover(function(){
                $(this).attr("title", "This image has been scaled down.  Click to view the original image.")
                $(this).css("cursor","pointer");
            });

            $(this).click(function(){
                window.location = $(this).attr("src");
            });
        } //ends if statement
    });
});

//Hat's off to Andy Clarke - http://forabeautifulweb.com/blog/about/trimming_form_fields_repost/
window.onload = function()
{
    if(document.getElementById && document.getElementById('linkContainer')) {
        var linkContainer = document.getElementById('linkContainer');
        var toggle = linkContainer.appendChild(document.createElement('a'));
        toggle.href = '#';
        toggle.appendChild(document.createTextNode('Remove optional fields?'));
        toggle.onclick = function()
      {
            var linkText = this.firstChild.nodeValue;
            this.firstChild.nodeValue = (linkText == 'Remove optional fields?') ? 'Display optional fields?' : 'Remove optional fields?';
            var tmp = document.getElementsByTagName('li');
            for (var i=0;i<tmp.length;i++)
            {
                if(tmp[i].className == 'optional')
                {
                    tmp[i].style.display = (tmp[i].style.display == 'none') ? 'block' : 'none';
                }
            }
            return false;
        }
    }
}

//Toggles n'gumph
$(document).ready(function(){
    //Hide (Collapse) the toggle containers on load
    $(".toggle_container").hide(); 

    //Switch the "Open" and "Close" state per click
    $(".trigger").toggle(function(){
        $(this).addClass("active");
    }, function () {
        $(this).removeClass("active");
    });

    //Slide up and down on click
    $(".trigger").click(function(){
        $(this).next(".toggle_container").slideToggle("medium");
        $("#loop_list").slideToggle("medium");
    });
});

jQuery(document).ready(function($){ 
    $('#basics-feeds > div, #basics-websites > div, #basics-interests > div, #company-specialisms > input, #socialnetworks > select').each(function(i)
    {
        $("input", this).each(function(i)
        {
            if (($(this).attr('type')=="text" || $(this).attr('type')=="select-one" || $(this).attr('type')=="---------") && $(this).val()=="" && $(this).attr('id').indexOf('0')=="-1")
            {
                $(this).parent().css({'display': 'none'});
            }
        });
    });
});

function addAnother(fieldname)
{
    $('#'+fieldname+' > div').each(function(i)
    {
        if ($(this).css('display') == 'none')
        {
            $(this).css({'display': ''});
            return false;
        }
    });
    return false;
}

/*-------------------------------------------------------------------- 
 * JQuery Plugin: "EqualHeights" by:	Scott Jehl, Todd Parker, Maggie Costello Wachs (http://www.filamentgroup.com) Copyright (c) 2008 Filament Group
 * Licensed under GPL (http://www.opensource.org/licenses/gpl-license.php)
--------------------------------------------------------------------*/
jQuery(document).ready(function($){ 	
	function equalHeight(group) {
		tallest = 0;
		group.each(function() {
			thisHeight = $(this).height();
			if(thisHeight > tallest) {
				tallest = thisHeight;
			}
		});
		group.height(tallest);
	}

	equalHeight($ ( ".directory_list .sep, #events_go ul" ) );
	
});

//Add class to elements that should have a pretty checkbox for delete
jQuery(document).ready(function($){
	$('#id_websites-0-DELETE, #id_websites-1-DELETE,#id_websites-2-DELETE, #id_websites-3-DELETE, #id_websites-4-DELETE, #id_websites-5-DELETE, #id_interests-0-DELETE, #id_interests-1-DELETE, #id_interests-2-DELETE, #id_interests-3-DELETE, #id_interests-4-DELETE, #id_interests-5-DELETE, #id_feeds-0-DELETE').addClass("styled");
});


//Make ampersands lush - may need adjusting
$(document).ready(function() {
    $("h1, h2, h3, h4, p:contains('&')", document.body)
        .contents()
        .each(
            function() {
                if( this.nodeType == 3 ) {
                    $(this)
                        .replaceWith( this
                            .nodeValue
                            .replace( /&/g, "<cite class='amp'>&amp;</cite>" )
                        );
                }
            }
        );
});

//Toggle my socks off
 $(document).ready(function(){
//close all the content divs on page load
$('.mover').hide();
// toggle slide
$('.button_me_up a').click(function(){
// by calling sibling, we can use same div for all demos
$(this).siblings('.mover').slideToggle();
});

});

//Do the Twitter dance

//String Helper Functions
// e.g. if (somestring.startsWith("/thehub/company_type/")) { ... }

String.prototype.startsWith = function(str)
	{return (this.match("^"+str)==str)}
String.prototype.endsWith = function(str)
	{return (this.match(str+"$")==str)}
String.prototype.trim = function(){return
	(this.replace(/^[\s\xA0]+/, "").replace(/[\s\xA0]+$/, ""))}



// Focus value
$(document).ready(function(){
    $('.val').each(function() {
        var default_value = this.value;
        $(this).focus(function() {
            if(this.value == default_value) {
                this.value = '';
            }
        });
        $(this).blur(function() {
            if(this.value == '') {
                this.value = default_value;
            }
        });
    });
});					
