function isValidEmailAddress(emailAddress) {
	var pattern = new RegExp(/^(("[\w-\s]+")|([\w-]+(?:\.[\w-]+)*)|("[\w-\s]+")([\w-]+(?:\.[\w-]+)*))(@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$)|(@\[?((25[0-5]\.|2[0-4][0-9]\.|1[0-9]{2}\.|[0-9]{1,2}\.))((25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\.){2}(25[0-5]|2[0-4][0-9]|1[0-9]{2}|[0-9]{1,2})\]?$)/i);
	return pattern.test(emailAddress);
}

function newsletter_signup(email) {
	$("#form_message").slideUp();
	if (isValidEmailAddress(email)) {
		$.post("/newsletter/", {email: email}, function(data) {
			if (data.indexOf("true") > -1) {
				$("#newsletter_signup_container").load("/newsletter_thanks");
			}
			else {
				$("#form_message").text("An error occured, please try agian later.").slideDown("slow");
			}
		});
	}
	else {
		$("#form_message").text("Please submit a valid e-mail address.").slideDown("slow");
		return false;
	}
}

var lastloc = window.location.href;

function generateBreadcrumb() {
	var loc = window.location.href;
	var current_breadcrumb = $("#breadcrumb > div.breadcrumb").html().toString().replace(/^\s*/, "").replace(/\s*$/, "");

	if (lastloc != loc)
	{
		var fragment = parse_url(loc,'PHP_URL_FRAGMENT');
		if (fragment === '')
		{
			var breadcrumb = '<a href="/" title="MindComet.com - The Relationship Agency" class="current">MindComet</a>';
			lastloc = loc;
		}
		else
		{
			var pieces = explode("/",fragment);
			var baseurl = "/";

			if ( (pieces.length <= 1) && (pieces[0] == "") )
			{
				var breadcrumb = '<a href="/" title="MindComet.com - The Relationship Agency" class="current">MindComet</a>';
			}
			else
			{
				var breadcrumb = '<a href="/" title="MindComet.com - The Relationship Agency">MindComet</a>';

				for (var i in pieces)
				{
					if ((pieces[i] != "") && (pieces[i] != "front") && (pieces[i] != "page_top"))
					{
						breadcrumb += " &gt; ";
						baseurl += pieces[i] + "/";
						title = pieces[i].replace(/-/g,' ');
						title = title.replace(/_/g, ' ');
						title = titleCaps(title);

						if (i == (pieces.length - 1) )
						{
							breadcrumb += '<a href="' + baseurl + '" class="current">' + title + '</a>';
						}
						else
						{
							breadcrumb += '<a href="' + baseurl + '">' + title + '</a>';
						}
					}
				}
			}
			lastloc = loc;
		}
		// don't replace breadcrumb if php-generated one is the same
		if (current_breadcrumb != breadcrumb)
		{
			replaceBreadcrumb(breadcrumb);
		}
	}
}


function replaceBreadcrumb(breadcrumb){
	// hide breadcrumb, replace it, show it.
	$("#breadcrumb > div.breadcrumb").fadeOut(function() {
		$(this).html(breadcrumb).fadeIn();
	});
}



function sharePortfolio(to,from,name,comments) {
	url = window.location.href;
	if ((to != "") && (from != "") && (name != "") && (comments != "")) {
		if (isValidEmailAddress(to) && isValidEmailAddress(from)) {
			$.post("/forms/shareportfolio",{to: to, from:from, name:name, comments:comments, url:url},function(data) {
				if (data.indexOf("success") > -1) {
					return true;
				} else {
					return false;
				}
			});
		}
	} else {
		return false;
	}	
}


function moreinfo(from,name,comments) {
	url = window.location.href;
	
	if ((from != "") && (name != "") && (comments != "")) {
		if (isValidEmailAddress(from)) {
			$.post("/forms/moreinfo",{from:from, name:name, comments:comments, url:url},function(data) {
				if (data.indexOf("success") > -1) {
					return true;
				} else {
					return false;
				}
			});
		}
	} else {
		return false;
	}	
}


//parse_url + explode both taken from phpjs
function parse_url (str, component) {
    // Parse a URL and return its components  (pulled from php.js)
    // 
    // *     example 1: parse_url('http://username:password@hostname/path?arg=value#anchor');
    // *     returns 1: {scheme: 'http', host: 'hostname', user: 'username', pass: 'password', path: '/path', query: 'arg=value', fragment: 'anchor'}
    var  o   = {
        strictMode: false,
        key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"],
        q:   {
            name:   "queryKey",
            parser: /(?:^|&)([^&=]*)=?([^&]*)/g
        },
        parser: {
            strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,
            loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/\/?)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // Added one optional slash to post-protocol to catch file:/// (should restrict this)
        }
    };
    
    var m   = o.parser[o.strictMode ? "strict" : "loose"].exec(str),
    uri = {},
    i   = 14;
    while (i--) {uri[o.key[i]] = m[i] || "";}
    // Uncomment the following to use the original more detailed (non-PHP) script
    /*
        uri[o.q.name] = {};
        uri[o.key[12]].replace(o.q.parser, function ($0, $1, $2) {
        if ($1) uri[o.q.name][$1] = $2;
        });
        return uri;
    */

    switch (component) {
        case 'PHP_URL_SCHEME':
            return uri.protocol;
        case 'PHP_URL_HOST':
            return uri.host;
        case 'PHP_URL_PORT':
            return uri.port;
        case 'PHP_URL_USER':
            return uri.user;
        case 'PHP_URL_PASS':
            return uri.password;
        case 'PHP_URL_PATH':
            return uri.path;
        case 'PHP_URL_QUERY':
            return uri.query;
        case 'PHP_URL_FRAGMENT':
            return uri.anchor;
        default:
            var retArr = {};
            if (uri.protocol !== '') {retArr.scheme=uri.protocol;}
            if (uri.host !== '') {retArr.host=uri.host;}
            if (uri.port !== '') {retArr.port=uri.port;}
            if (uri.user !== '') {retArr.user=uri.user;}
            if (uri.password !== '') {retArr.pass=uri.password;}
            if (uri.path !== '') {retArr.path=uri.path;}
            if (uri.query !== '') {retArr.query=uri.query;}
            if (uri.anchor !== '') {retArr.fragment=uri.anchor;}
            return retArr;
    }
}


function explode( delimiter, string, limit ) {
    // Splits a string on string separator and return array of components. If limit is positive only limit number of components is returned. If limit is negative all components except the last abs(limit) are returned.  
    var emptyArray = { 0: '' };
    
    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' )
    {
        return null;
    }
 
    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null )
    {
        return false;
    }
 
    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' )
    {
        return emptyArray;
    }
 
    if ( delimiter === true ) {
        delimiter = '1';
    }
    
    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}


function get_footer_height(){
	minimum_height = 590;
	footer_height = $('#footer').height();
	total_height = $('body').height();
	new_flash_height = Math.max(minimum_height, (total_height - footer_height - 20));
	$('#dashboard').height(new_flash_height);
}

/*
 * Title Caps
 * 
 * Ported to JavaScript By John Resig - http://ejohn.org/ - 21 May 2008
 * Original by John Gruber - http://daringfireball.net/ - 10 May 2008
 * License: http://www.opensource.org/licenses/mit-license.php
 */

(function(){
	var small = "(a|an|and|as|at|but|by|en|for|if|in|of|on|or|the|to|v[.]?|via|vs[.]?)";
	var punct = "([!\"#$%&'()*+,./:;<=>?@[\\\\\\]^_`{|}~-]*)";
	
	this.titleCaps = function(title){
		var parts = [], split = /[:.;?!] |(?: |^)["Ò]/g, index = 0;
		
		while (true) {
			var m = split.exec(title);
			
			parts.push( title.substring(index, m ? m.index : title.length)
				.replace(/\b([A-Za-z][a-z.'Õ]*)\b/g, function(all){
					return /[A-Za-z]\.[A-Za-z]/.test(all) ? all : upper(all);
				})
				.replace(RegExp("\\b" + small + "\\b", "ig"), lower)
				.replace(RegExp("^" + punct + small + "\\b", "ig"), function(all, punct, word){
					return punct + upper(word);
				})
				.replace(RegExp("\\b" + small + punct + "$", "ig"), upper));
			
			index = split.lastIndex;
			
			if ( m ) parts.push( m[0] );
			else break;
		}
		
		return parts.join("").replace(/ V(s?)\. /ig, " v$1. ")
			.replace(/(['Õ])S\b/ig, "$1s")
			.replace(/\b(AT&T|Q&A)\b/ig, function(all){
				return all.toUpperCase();
			});
	};
    
	function lower(word){
		return word.toLowerCase();
	}
    
	function upper(word){
	  return word.substr(0,1).toUpperCase() + word.substr(1);
	}
})();


$(document).ready(function() {
	// regenerate the breadcrumb on an interval
	self.setInterval("generateBreadcrumb()",1000);
	
	// Open all external links in new window
	$.fn.external = function() {
		$(this).live('click', function() {
			if (!$(this).is('[href*=mindcomet.com], [href*=mindcomet.net]'))
			{
				return !window.open(this.href);
			}
		});
	};

	// Set initial external links
	$('a[href^=http]').external();

	FLIR.init( { path: '/_assets/facelift/' } );
	FLIR.replace('.museo', new FLIRStyle({mode:'wrap'}));
	
	$("#newsletter_signup_container #form_javascript_message").hide();
	$("#newsletter_signup #newsletter_submit_button").removeAttr("disabled");
	$("#newsletter_signup :submit").live('click', function(e) {
		e.preventDefault();
		newsletter_signup($("#email", $(this).parents('#newsletter_signup')).val());
	});
	
	$("#newsletter_signup input[type=text]").live('keypress', function(e) {
		if (e.which == 13)
		{
			e.preventDefault();
			newsletter_signup($("#email", $(this).parents('#newsletter_signup')).val());
		}
	});
		
});
