// http://www.JSON.org/json2.js 2011-02-23
var JSON;if(!JSON){JSON={};}(function(){"use strict";function f(n){return n<10?'0'+n:n;}if(typeof Date.prototype.toJSON!=='function'){Date.prototype.toJSON=function(key){return isFinite(this.valueOf())?this.getUTCFullYear()+'-'+f(this.getUTCMonth()+1)+'-'+f(this.getUTCDate())+'T'+f(this.getUTCHours())+':'+f(this.getUTCMinutes())+':'+f(this.getUTCSeconds())+'Z':null;};String.prototype.toJSON=Number.prototype.toJSON=Boolean.prototype.toJSON=function(key){return this.valueOf();};}var cx=/[\u0000\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,escapable=/[\\\"\x00-\x1f\x7f-\x9f\u00ad\u0600-\u0604\u070f\u17b4\u17b5\u200c-\u200f\u2028-\u202f\u2060-\u206f\ufeff\ufff0-\uffff]/g,gap,indent,meta={'\b':'\\b','\t':'\\t','\n':'\\n','\f':'\\f','\r':'\\r','"':'\\"','\\':'\\\\'},rep;function quote(string){escapable.lastIndex=0;return escapable.test(string)?'"'+string.replace(escapable,function(a){var c=meta[a];return typeof c==='string'?c:'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);})+'"':'"'+string+'"';}function str(key,holder){var i,k,v,length,mind=gap,partial,value=holder[key];if(value&&typeof value==='object'&&typeof value.toJSON==='function'){value=value.toJSON(key);}if(typeof rep==='function'){value=rep.call(holder,key,value);}switch(typeof value){case'string':return quote(value);case'number':return isFinite(value)?String(value):'null';case'boolean':case'null':return String(value);case'object':if(!value){return'null';}gap+=indent;partial=[];if(Object.prototype.toString.apply(value)==='[object Array]'){length=value.length;for(i=0;i<length;i+=1){partial[i]=str(i,value)||'null';}v=partial.length===0?'[]':gap?'[\n'+gap+partial.join(',\n'+gap)+'\n'+mind+']':'['+partial.join(',')+']';gap=mind;return v;}if(rep&&typeof rep==='object'){length=rep.length;for(i=0;i<length;i+=1){if(typeof rep[i]==='string'){k=rep[i];v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}else{for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=str(k,value);if(v){partial.push(quote(k)+(gap?': ':':')+v);}}}}v=partial.length===0?'{}':gap?'{\n'+gap+partial.join(',\n'+gap)+'\n'+mind+'}':'{'+partial.join(',')+'}';gap=mind;return v;}}if(typeof JSON.stringify!=='function'){JSON.stringify=function(value,replacer,space){var i;gap='';indent='';if(typeof space==='number'){for(i=0;i<space;i+=1){indent+=' ';}}else if(typeof space==='string'){indent=space;}rep=replacer;if(replacer&&typeof replacer!=='function'&&(typeof replacer!=='object'||typeof replacer.length!=='number')){throw new Error('JSON.stringify');}return str('',{'':value});};}if(typeof JSON.parse!=='function'){JSON.parse=function(text,reviver){var j;function walk(holder,key){var k,v,value=holder[key];if(value&&typeof value==='object'){for(k in value){if(Object.prototype.hasOwnProperty.call(value,k)){v=walk(value,k);if(v!==undefined){value[k]=v;}else{delete value[k];}}}}return reviver.call(holder,key,value);}text=String(text);cx.lastIndex=0;if(cx.test(text)){text=text.replace(cx,function(a){return'\\u'+('0000'+a.charCodeAt(0).toString(16)).slice(-4);});}if(/^[\],:{}\s]*$/.test(text.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,'@').replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,']').replace(/(?:^|:|,)(?:\s*\[)+/g,''))){j=eval('('+text+')');return typeof reviver==='function'?walk({'':j},''):j;}throw new SyntaxError('JSON.parse');};}}());



// http://code.google.com/p/javascriptbase64/ - JT Mods
(function(){function StringBuffer(){this.buffer=[];}StringBuffer.prototype.append=function append(string){this.buffer.push(string);return this;};StringBuffer.prototype.toString=function toString(){return this.buffer.join("");};window.Base64={codex:"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=",encode:function(input){var output=new StringBuffer();var enumerator=new Utf8EncodeEnumerator(input);while(enumerator.moveNext()){var chr1=enumerator.current;enumerator.moveNext();var chr2=enumerator.current;enumerator.moveNext();var chr3=enumerator.current;var enc1=chr1>>2;var enc2=((chr1&3)<<4)|(chr2>>4);var enc3=((chr2&15)<<2)|(chr3>>6);var enc4=chr3&63;if(isNaN(chr2)){enc3=enc4=64;}else if(isNaN(chr3)){enc4=64;}output.append(this.codex.charAt(enc1)+this.codex.charAt(enc2)+this.codex.charAt(enc3)+this.codex.charAt(enc4));}return output.toString();},decode:function(input){var output=new StringBuffer();var enumerator=new Base64DecodeEnumerator(input);while(enumerator.moveNext()){var charCode=enumerator.current;if(charCode<128){output.append(String.fromCharCode(charCode));}else if((charCode>191)&&(charCode<224)){enumerator.moveNext();var charCode2=enumerator.current;output.append(String.fromCharCode(((charCode&31)<<6)|(charCode2&63)));}else{enumerator.moveNext();var charCode2=enumerator.current;enumerator.moveNext();var charCode3=enumerator.current;output.append(String.fromCharCode(((charCode&15)<<12)|((charCode2&63)<<6)|(charCode3&63)));}}return output.toString();}};function Utf8EncodeEnumerator(input){this._input=input;this._index=-1;this._buffer=[];}Utf8EncodeEnumerator.prototype={current:Number.NaN,moveNext:function(){if(this._buffer.length>0){this.current=this._buffer.shift();return true;}else if(this._index>=(this._input.length-1)){this.current=Number.NaN;return false;}else{var charCode=this._input.charCodeAt(++this._index);if((charCode==13)&&(this._input.charCodeAt(this._index+1)==10)){charCode=10;this._index+=2;}if(charCode<128){this.current=charCode;}else if((charCode>127)&&(charCode<2048)){this.current=(charCode>>6)|192;this._buffer.push((charCode&63)|128);}else{this.current=(charCode>>12)|224;this._buffer.push(((charCode>>6)&63)|128);this._buffer.push((charCode&63)|128);}return true;}}};function Base64DecodeEnumerator(input){this._input=input;this._index=-1;this._buffer=[];}Base64DecodeEnumerator.prototype={current:64,moveNext:function(){if(this._buffer.length>0){this.current=this._buffer.shift();return true;}else if(this._index>=(this._input.length-1)){this.current=64;return false;}else{var enc1=Base64.codex.indexOf(this._input.charAt(++this._index));var enc2=Base64.codex.indexOf(this._input.charAt(++this._index));var enc3=Base64.codex.indexOf(this._input.charAt(++this._index));var enc4=Base64.codex.indexOf(this._input.charAt(++this._index));var chr1=(enc1<<2)|(enc2>>4);var chr2=((enc2&15)<<4)|(enc3>>2);var chr3=((enc3&3)<<6)|enc4;this.current=chr1;if(enc3!=64){this._buffer.push(chr2);}if(enc4!=64){this._buffer.push(chr3);}return true;}}};})();



// method to uppercase first letter of each word
String.prototype.ucwords = function(){
    return this.replace(/(^|\s+)[a-z]/g, function(c){
        return c.toUpperCase();
    });
};



// open all external links in a new window
(function($){
    $('body').delegate('a', 'click', function(e){
        if ((/^https?\:$/i).test(this.protocol) && this.hostname && this.hostname !== location.hostname) {
            e.preventDefault();
            window.open(this.href);
        }
    });
})(jQuery);



// underline active nav link
(function($){
    $('#nav a').each(function(){
        if (this.hostname === location.hostname && (this.pathname === location.pathname || '/' + this.pathname === location.pathname)) {
            $(this).addClass('active');
        }
    });
})(jQuery);



// Email Form BETA
jQuery.emailForm = function(selector){

    // placeholder text
    $(selector).find('input[type="text"], textarea').each(function(){
        var ph = $(this).attr('name').ucwords();
        $(this).blur(function(){
            if (!$(this).val()) {
                $(this).val(ph);
            }
        });
        $(this).focus(function(){
            if ($(this).val() == ph) {
                $(this).val('');
            }
        });
        $(this).trigger('blur');
    });

    // send email
    $(selector).find('[name="send"]').click(function(e){

        // make sure everything is filled out
        $(selector).find('input[type="text"], textarea').each(function(){
            var ph = $(this).attr('name').ucwords();
            if ($(this).val() == ph || !$(this).val()) {
                alert('Please complete all the fields!');
                return false;
            }
        });

        // contruct email object
        var data, email = {
            from: {
                name: $(selector).find('input[name="name"]').val(),
                email: $(selector).find('input[name="email"]').val()
            },
            subject: '[' + location.hostname.ucwords() + '] ' + $(selector).find('input[name="subject"]').val(),
            message: $(selector).find('textarea[name="message"]').val()
        };

        if (!(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i).test(email.from.email)) {
            alert('Please enter a valid email address!');
        } else {
            data = Base64.encode(JSON.stringify(email)).replace(/\+/g, '-').replace(/\//g, '_');
            $.getJSON('https://terenz.io/n/email/?data='+data+'&callback=?', function(response){
            if (response && response.success) {
                    alert('Your message has been sent!');
                    location = '/';
                } else {
                    alert('There was an error sending your message.');
                }
            });
        }
    });
};

$.emailForm('#contact');
