/*
 * Author: Karl O'Leary
 * Description: Specific logic 
 */

var map = null;

/*
 * On load code.
 */
jQuery(document).ready(function() {
    
    /*
    Cufon.replace('ul.main_nav li a',{fontFamily:'DIN 1451'});
    Cufon.replace('h2',{fontFamily:'DIN 1451'});
    Cufon.now();
    */
    
    
    // contact page
    // unable use the jQuery.url plugin at the moment
    try {
        jQuery("div.feeds p").getTwitter({
            userName: "davesredheaven",
            numTweets: 1,
            loaderText: "Loading tweets...",
            slideIn: false,
            showHeading: false,
            showProfileLink: true,
            showTimestamp: false
        });


        if (GBrowserIsCompatible()) {
            map = new GMap2(document.getElementById('map'));
            map.addControl(new GLargeMapControl());
            map.addControl(new GMapTypeControl());
            map.setCenter(new GLatLng(52.138057, -7.931269), 17);

            var marker = new GMarker(new GLatLng(52.138057, -7.931269));
            GEvent.addListener(marker, 'click', function() { marker.openInfoWindowHtml('<p><em>Red Heaven Design</em></p>'); });
            map.addOverlay(marker);
        }
    }
    catch(err) {}

    // newsletter signup
    jQuery("form.newsletter input").bind("click", function() {
       jQuery(this).val("");
    });
    jQuery("form.newsletter").bind("submit", function() {
        var email = jQuery("input", this).val();
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(email)) {
            jQuery.ajax({
                async: false,
                url: "http://www.redheavendesign.com/actions/signup",
                type: 'post',
                data: 'email='+email,
                error: function() { alert("There was blip in machine\n\nPlease try again."); },
                success: function(data) {
                    if (data=="200") alert("Thank you for your interest\n\nI will be in touch shortly.");
                    else alert("There was blip in machine\nPlease try again.");
                }
            });
            jQuery("form.newsletter input").val("Email me here.");
        }
        else
            alert('Please enter a valid email address');
        return false;
    });

    // hire me
    jQuery("form.hireme input").bind("click", function() {
       jQuery(this).val("");
    });
    jQuery("form.hireme").bind("submit", function() {
        var email = jQuery("input", this).val();
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(email)) {
            jQuery.ajax({
                async: false,
                url: "http://www.redheavendesign.com/actions/hireme",
                type: 'post',
                data: 'email='+email,
                error: function() { alert("There was blip in machine\n\nPlease try again."); },
                success: function(data) {
                    if (data=="200") alert("Thank you for your interest\n\nI will be in touch shortly.");
                    else alert("There was blip in machine\nPlease try again.");
                }
            });
            jQuery("form.hireme input").val("Email me here.");
        }
        else
            alert('Please enter a valid email address');
        return false;
    });
    

    // contact form
    jQuery("#save_contact button").bind("click", function() {
        var name = jQuery("#name").val();
        var phone = jQuery("#phone").val();
        var email = jQuery("#email").val();
        var message = jQuery("#message").val();
        var captcha = jQuery("#captcha").val();
        var filter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
        if (filter.test(email)) {            
            jQuery.ajax({
                async: false,
                url: "http://www.redheavendesign.com/actions/save_contact",
                type: 'post',
                data: 'name='+name+'&phone='+phone+'&email='+email+'&message='+message+'&captcha='+captcha,
                error: function() { alert("There was blip in machine\n\nPlease try again."); },
                success: function(data) {
                	if (data=="200") {
                    	jQuery("#name").val("");
                        jQuery("#phone").val("");
                        jQuery("#email").val("");
                        jQuery("#message").val("");
                        jQuery("#captcha").val("");
                    	alert("Thank you for your interest\n\nI will be in touch shortly.");
                    }
                    else if (data=="204") alert("Please try the Captcha again.");
                    else alert("There was blip in machine\n\nPlease try again.");
                }
            });
        }
        else
            alert('Please enter a valid email address');
        return false;
    });
});

/*
 * On close code.
 */
jQuery(window).unload(function () {
    if (jQuery.url.segment(1)=="contact")
        GUnload();
});

// ============================================================================= jquery.url.js

jQuery.url = function()
{
	var segments = {};

	var parsed = {};

	/**
    * Options object. Only the URI and strictMode values can be changed via the setters below.
    */
  	var options = {

		url : window.location, // default URI is the page in which the script is running

		strictMode: false, // 'loose' parsing by default

		key: ["source","protocol","authority","userInfo","user","password","host","port","relative","path","directory","file","query","anchor"], // keys available to query

		q: {
			name: "queryKey",
			parser: /(?:^|&)([^&=]*)=?([^&]*)/g
		},

		parser: {
			strict: /^(?:([^:\/?#]+):)?(?:\/\/((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?))?((((?:[^?#\/]*\/)*)([^?#]*))(?:\?([^#]*))?(?:#(.*))?)/,  //less intuitive, more accurate to the specs
			loose:  /^(?:(?![^:@]+:[^:@\/]*@)([^:\/?#.]+):)?(?:\/\/)?((?:(([^:@]*):?([^:@]*))?@)?([^:\/?#]*)(?::(\d*))?)(((\/(?:[^?#](?![^?#\/]*\.[^?#\/.]+(?:[?#]|$)))*\/?)?([^?#\/]*))(?:\?([^#]*))?(?:#(.*))?)/ // more intuitive, fails on relative paths and deviates from specs
		}

	};

    /**
     * Deals with the parsing of the URI according to the regex above.
 	 * Written by Steven Levithan - see credits at top.
     */
	var parseUri = function()
	{
		str = decodeURI( options.url );

		var m = options.parser[ options.strictMode ? "strict" : "loose" ].exec( str );
		var uri = {};
		var i = 14;

		while ( i-- ) {
			uri[ options.key[i] ] = m[i] || "";
		}

		uri[ options.q.name ] = {};
		uri[ options.key[12] ].replace( options.q.parser, function ( $0, $1, $2 ) {
			if ($1) {
				uri[options.q.name][$1] = $2;
			}
		});

		return uri;
	};

    /**
     * Returns the value of the passed in key from the parsed URI.
  	 *
	 * @param string key The key whose value is required
     */
	var key = function( key )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...
		}
		if ( key == "base" )
		{
			if ( parsed.port !== null && parsed.port !== "" )
			{
				return parsed.protocol+"://"+parsed.host+":"+parsed.port+"/";
			}
			else
			{
				return parsed.protocol+"://"+parsed.host+"/";
			}
		}

		return ( parsed[key] === "" ) ? null : parsed[key];
	};

	/**
     * Returns the value of the required query string parameter.
  	 *
	 * @param string item The parameter whose value is required
     */
	var param = function( item )
	{
		if ( ! parsed.length )
		{
			setUp(); // if the URI has not been parsed yet then do this first...
		}
		return ( parsed.queryKey[item] === null ) ? null : parsed.queryKey[item];
	};

    /**
     * 'Constructor' (not really!) function.
     *  Called whenever the URI changes to kick off re-parsing of the URI and splitting it up into segments.
     */
	var setUp = function()
	{
		parsed = parseUri();

		getSegments();
	};

    /**
     * Splits up the body of the URI into segments (i.e. sections delimited by '/')
     */
	var getSegments = function()
	{
		var p = parsed.path;
		segments = []; // clear out segments array
		segments = parsed.path.length == 1 ? {} : ( p.charAt( p.length - 1 ) == "/" ? p.substring( 1, p.length - 1 ) : path = p.substring( 1 ) ).split("/");
	};

	return {

	    /**
	     * Sets the parsing mode - either strict or loose. Set to loose by default.
	     *
	     * @param string mode The mode to set the parser to. Anything apart from a value of 'strict' will set it to loose!
	     */
		setMode : function( mode )
		{
			strictMode = mode == "strict" ? true : false;
			return this;
		},

		/**
	     * Sets URI to parse if you don't want to to parse the current page's URI.
		 * Calling the function with no value for newUri resets it to the current page's URI.
	     *
	     * @param string newUri The URI to parse.
	     */
		setUrl : function( newUri )
		{
			options.url = newUri === undefined ? window.location : newUri;
			setUp();
			return this;
		},

		/**
	     * Returns the value of the specified URI segment. Segments are numbered from 1 to the number of segments.
		 * For example the URI http://test.com/about/company/ segment(1) would return 'about'.
		 *
		 * If no integer is passed into the function it returns the number of segments in the URI.
	     *
	     * @param int pos The position of the segment to return. Can be empty.
	     */
		segment : function( pos )
		{
			if ( ! parsed.length )
			{
				setUp(); // if the URI has not been parsed yet then do this first...
			}
			if ( pos === undefined )
			{
				return segments.length;
			}
			return ( segments[pos] === "" || segments[pos] === undefined ) ? null : segments[pos];
		},

		attr : key, // provides public access to private 'key' function - see above

		param : param // provides public access to private 'param' function - see above

	};

}();



// ============================================================================= twitter

(function($) {
	/*
		jquery.twitter.js v1.5
		Last updated: 08 July 2009

		Created by Damien du Toit
		http://coda.co.za/blog/2008/10/26/jquery-plugin-for-twitter

		Licensed under a Creative Commons Attribution-Non-Commercial 3.0 Unported License
		http://creativecommons.org/licenses/by-nc/3.0/
	*/

	$.fn.getTwitter = function(options) {

		$.fn.getTwitter.defaults = {
			userName: null,
			numTweets: 5,
			loaderText: "Loading tweets...",
			slideIn: true,
			slideDuration: 750,
			showHeading: true,
			headingText: "Our Latest Tweets",
			showProfileLink: true,
			showTimestamp: true
		};

		var o = $.extend({}, $.fn.getTwitter.defaults, options);

		return this.each(function() {
			var c = $(this);

			// hide container element, remove alternative content, and add class
			c.hide().empty().addClass("twitted");

			// add heading to container element
			if (o.showHeading) {
				c.append("<h2>"+o.headingText+"</h2>");
			}

			// add twitter list to container element
			var twitterListHTML = "<ul id=\"twitter_update_list\"><li></li></ul>";
			c.append(twitterListHTML);

			var tl = $("#twitter_update_list");

			// hide twitter list
			tl.hide();

			// add preLoader to container element
			var preLoaderHTML = $("<p class=\"preLoader\">"+o.loaderText+"</p>");
			c.append(preLoaderHTML);

			// add Twitter profile link to container element
			if (o.showProfileLink) {
				var profileLinkHTML = ""; //<p class=\"profileLink\"><a href=\"http://twitter.com/"+o.userName+"\">Checkout all of my tweets @ http://twitter.com/"+o.userName+"</a></p>";
				c.append(profileLinkHTML);
			}

			// show container element
			c.show();

			$.getScript("http://twitter.com/javascripts/blogger.js");
			$.getScript("http://twitter.com/statuses/user_timeline/"+o.userName+".json?callback=twitterCallback2&count="+o.numTweets, function() {
				// remove preLoader from container element
				$(preLoaderHTML).remove();

				// remove timestamp and move to title of list item
				if (!o.showTimestamp) {
					tl.find("li").each(function() {
						var timestampHTML = $(this).children("a");
						var timestamp = timestampHTML.html();
						timestampHTML.remove();
						$(this).attr("title", timestamp);
					});
				}

				// show twitter list
				if (o.slideIn) {
					// a fix for the jQuery slide effect
					// Hat-tip: http://blog.pengoworks.com/index.cfm/2009/4/21/Fixing-jQuerys-slideDown-effect-ie-Jumpy-Animation
					var tlHeight = tl.data("originalHeight");

					// get the original height
					if (!tlHeight) {
						tlHeight = tl.show().height();
						tl.data("originalHeight", tlHeight);
						tl.hide().css({height: 0});
					}

					tl.show().animate({height: tlHeight}, o.slideDuration);
				}
				else {
					tl.show();
				}

				// add unique class to first list item
				tl.find("li:first").addClass("firstTweet");

				// add unique class to last list item
				tl.find("li:last").addClass("lastTweet");
			});
		});
	};
})(jQuery);
