﻿// --- Util functions --- \\
var createnamespace = function() {
    var o, d;
    $.each(arguments, function(v) {
        d = arguments[1].split(".");
        o = window[d[0]] = window[d[0]] || {};
        $.each(d.slice(1), function(v2) {
            o = o[arguments[1]] = o[arguments[1]] || {};
        });
    });
    return o;
}

String.prototype.beginsWith = function(t, i) {
    if (i == false) {
        return (t == this.substring(0, t.length));
    } else {
        return (t.toLowerCase() == this.substring(0, t.length).toLowerCase());
    }
}

String.prototype.endsWith = function(t, i) {
    if (i == false) {
        return (t == this.substring(this.length - t.length));
    } else {
        return (t.toLowerCase() == this.substring(this.length - t.length).toLowerCase());
    }
}

String.format = function(text) {
    //check if there are two arguments in the arguments list
    if (arguments.length <= 1) {
        //if there are not 2 or more arguments there’s nothing to replace
        //just return the original text
        return text;
    }

    //decrement to move to the second argument in the array
    var tokenCount = arguments.length - 2;
    for (var token = 0; token <= tokenCount; token++) {
        //iterate through the tokens and replace their placeholders from the original text in order
        text = text.replace(new RegExp("\\{" + token + "\\}", "gi"), arguments[token + 1]);
    }
    return text;
}

Date.deserialiseFromJSON = function(jsonDate) {
    return eval('new' + jsonDate.replace(/\//g, ' '));
}

var isNull = function(object) {
    return typeof object == "undefined" || object === null || object === '';
}

// --- User-initiated interactions --- \\
$(document).ready(function() {

   // --- ENQUIRY FORM --- \\
   var showEnquiryForm = function(e){
        e.preventDefault();

        var trackUrl = "/contact/enquiry-form/";
        _gaq.push(['_trackPageview', trackUrl]);        
        
        var size = { 
            w : "575",
            h : ( $.browser.msie ) ? "585" : "565"
        }

        $.fn.colorbox({
            href: trackUrl,
            title: "Please get in touch...",
            iframe: true,
            width: size.w,
            height: size.h,
            initialWidth: size.w,
            initialHeight: size.h,
            opacity: 0.5,
            transition: 0,
            speed: 0,
            close: "<span>Close Window</span> <strong>X</strong>"
        });
   }
    // attach events - generic
   $(".enquiryForm").click ( showEnquiryForm );

   // --- PDF FORM --- \\
   var showPdfForm = function ( e ) {
        e.preventDefault();

        var trackUrl = "/contact/enquiry-form/pdf";
        _gaq.push(['_trackPageview', trackUrl]);    
        
        var size = { 
            w : "575",
            h : ( $.browser.msie ) ? "355" : "345"
        }

        $.fn.colorbox({
            href: trackUrl,
            title: "Download Brochure",
            iframe: true,
            width: size.w,
            height: size.h,
            initialWidth: size.w,
            initialHeight: size.h,
            opacity: 0.5,
            transition: 0,
            speed: 0,
            close: "<span>Close Window</span> <strong>X</strong>"
        });
    }
     
   // attach events - sidebar
   $(".brochurePanel .brochurePanelImage a").click(showPdfForm);
   $(".brochurePanelBlurb .dl").click(showPdfForm);
   // attach events - generic
   $(".pdfForm").click(showPdfForm);

   // --- AJAX NEWSLETTER SIGN-UP --- \\
   var origText = $("#nlEmail").val();
   $("#nlEmail").focus(function(){ $(this).val(""); })
   
   $("#newsletterForm").validate({ 
        errorElement : "em",
        submitHandler: function(form) {   
            $("#nlLoader").show();             
            $.ajax({
               type: "POST",
               url: "/contact/newslettersignup",
               data: { "emailAddress" : $("#nlEmail").val() },
               success: function( data ){
                   $("#nlEmail").val( origText );
                   $("#nlLoader").hide();    
                   alert("Thanks for signing up!");                   
               }
            });
        }
    })

    $(".showBrochure a").click(function(e){        
        var trackUrl = $(this).attr("href");        
        _gaq.push(['_trackPageview', trackUrl]);
        _gaq.push(['_trackEvent', 'Downloads', 'PDF', trackUrl]);
    });

    $("#cancel").click(function(e) {
        e.preventDefault();                  
        parent.$.fn.colorbox.close()
    });
    
    // --- auto fill (split email to create name)
    var runOnce = false;    
    $("#email").blur(function(){
        if ( !runOnce && !isNull ( $(this).val() ) ) {
            var splitEmail = $(this).val().split("@");
            if ( splitEmail.length == 2 ) {
                var bothNames = splitEmail[0].split(".");
                if ( bothNames.length == 2 ) { 
                    $("#first_name").val( bothNames[0] );
                    $("#last_name").val( bothNames[1] );
                };
            };
            runOnce=true;
        }     
    });
      

});
