$("#photo-gallery li a").attr({
    "rel": "gallery",
    "class": "gallery"
})
$(".gallery").fancybox({
    titleShow: true,
    titlePosition: 'inside'
});

// Hide and show text input values
$(".default-value").each(function() {
    var defaultValue = this.value;
    $(this).focus(function() {
        if(this.value == defaultValue) {
            this.value = '';
        }
    });
    $(this).blur(function() {
        if(this.value == '') {
            this.value = defaultValue;
        }
    });
});

$("#quotes").cycle ({
    timeout: 3000,
    fx: 'fade'
});
    
// Open external links in a new window
$("a[href^='http:']").attr('target','_blank');

$("#home-slide-show").cycle();


$("#slide-show").after('<div id="slide-pager">').cycle({ 
    pager:  '#slide-pager',
    pagerAnchorBuilder: function(idx, slide) { 
        return '<span></span>'; 
    }
});

Cufon.replace('#nav > ul > li > a', {
    hover: true,
    fontFamily: "Antique3"
})

Cufon.replace('.sub-nav > ul > li > a', {
    hover: true,
    textShadow: "1px 1px 2px #666",
    fontFamily: "Antique3"
})

// Cufon.replace('#main h2, #main h3', {
//     fontFamily: "Sheldrake JNL"
// })
// 
// 


// Stick sidebar
$("#side").before('<span class="stick"></span>');

function stickSide() {
    var offset = $(".stick").offset();
    var so = offset.top;
    var st = $(window).scrollTop();
    
    if ( $(window).height() < 680 ) {
        return; // don't bother
    } else {
        if ( so < st ) {
            $("#side").css({
                "position": "fixed",
                "top": 20
            });
            //console.log(so)
        } else {
            $("#side").css({
                "position": "relative",
                "top": 0
            });

        }
    }
}

if ( ! $(".stick").length == 0 ) {
    $(window).scroll(function(){
        stickSide();
    })
}

/*  Submit e-list form via ajax
------------------------------------------------------------------------ */

// Check for valid email
function checkEmail(email) { 
  var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var emailVal = $("#" + email).val();
  return pattern.test(emailVal);
}

// Sumbit e-list sign-up via ajax
$("#footer #elist-form input:image").click(function() { 
  
  // First, disable the form from submitting
  $('form#elist-form').submit(function() { return false; });
  
  // Grab form action
  var formAction = $("form#elist-form").attr("action");
  
  // Hacking together id for email field
  // Replace the xxxxx below:
  // If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
  var id = "ktuuhr";
  var emailId = id + "-" + id;
  // Validate email address with regex
  if (!checkEmail(emailId)) {
    alert("Please enter a valid email address");
    return;
  }
  
  // Serialize form values to be submitted with POST
  var str = $("form#elist-form").serialize();
  
  // Add form action to end of serialized data
  // CDATA is used to avoid validation errors
  //<![CDATA[
  var serialized = str + "&action=" + formAction;
  // ]]>
  
  // Submit the form via ajax
  $.ajax({
    url: "php/proxy.php",
    type: "POST",
    data: serialized,
    success: function(data){
      // Server-side validation
      if (data.search(/invalid/i) != -1) {
        alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
      }
      else
      {
        $("#elist-form").hide(); // If successfully submitted hides the form
        $("#confirmation").fadeIn("slow");  // Shows "Thanks for subscribing" div
        $("#confirmation").tabIndex = -1;
        $("#confirmation").focus(); // For screen reader accessibility
        // Fire off Google Analytics fake pageview
        //var pageTracker = _gat._getTracker("UA-XXXXX-X");
        //pageTracker._trackPageview("/newsletter_signup");
      }
    }
  });
});

/*  Submit e-list form via ajax
------------------------------------------------------------------------ */

// Check for valid email
function checkEmail(email) { 
  var pattern = /^([a-zA-Z0-9_\.\-\+])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/;
  var emailVal = $("#" + email).val();
  return pattern.test(emailVal);
}

// Sumbit e-list sign-up via ajax
$("#home-page #elist-form input:image").click(function() { 
  
  // First, disable the form from submitting
  $('form#elist-form').submit(function() { return false; });
  
  // Grab form action
  var formAction = $("form#elist-form").attr("action");
  
  // Hacking together id for email field
  // Replace the xxxxx below:
  // If your form action were http://mysiteaddress.createsend.com/t/r/s/abcde/, then you'd enter "abcde" below
  var id = "nulhkt";
  var emailId = id + "-" + id;
  // Validate email address with regex
  if (!checkEmail(emailId)) {
    alert("Please enter a valid email address");
    return;
  }
  
  // Serialize form values to be submitted with POST
  var str = $("form#elist-form").serialize();
  
  // Add form action to end of serialized data
  // CDATA is used to avoid validation errors
  //<![CDATA[
  var serialized = str + "&action=" + formAction;
  // ]]>
  
  // Submit the form via ajax
  $.ajax({
    url: "php/proxy.php",
    type: "POST",
    data: serialized,
    success: function(data){
      // Server-side validation
      if (data.search(/invalid/i) != -1) {
        alert('The email address you supplied is invalid and needs to be fixed before you can subscribe to this list.');
      }
      else
      {
        $("#elist-form").hide(); // If successfully submitted hides the form
        $("#confirmation").fadeIn("slow");  // Shows "Thanks for subscribing" div
        $("#confirmation").tabIndex = -1;
        $("#confirmation").focus(); // For screen reader accessibility
        // Fire off Google Analytics fake pageview
        //var pageTracker = _gat._getTracker("UA-XXXXX-X");
        //pageTracker._trackPageview("/newsletter_signup");
      }
    }
  });
});

/*  Home page video
------------------------------------------------------------------------ */
    

function launchVideo() {
    
    // var progress = $("#progress-bar");
    // var elapsed = $("#elapsed");
    
    $("#media-player-wrapper").show()
    $("body").append('<div id="overlay">')
    $("#overlay").css({
        "position": "absolute",
        "top": 0,
        "left": 0,
        "width": $(document).width(),
        "height": $(document).height(),
        "background-color": "#000000",
        "opacity": 0.8,
        "z-index": 1010
    })
    
    var flashvars = {};
    var params = {
            play: "true",
            wmode: "transparent",
            allowscriptaccess: "always"
        }
    var attributes = {};
    swfobject.embedSWF("http://www.youtube.com/apiplayer?enablejsapi=1&version=3", "media-player-object", "900", "531", "9.0.0", false, flashvars, params, attributes);

    $("#media-controls, #btn-close").show()
    $("#btn-get-tix").addClass("video-playing")
    $("#quotes").hide()
}

function onPlayerStateChange(newState) {
    if ( newState == 0 ) {
        
        $("#media-player-wrapper").hide()
        $("#overlay").remove();
        $("#btn-get-tix").removeClass("video-playing");
        $("#quotes").show()
    }
}

function playVideo() {
  if (ytplayer) {
    ytplayer.playVideo();
  }
}

function pauseVideo() {
  if (ytplayer) {
    ytplayer.pauseVideo();
  }
}

function stopVideo() {
    if (ytplayer) {
        ytplayer.stopVideo();
    }
}

function closeVideo() {
    ytplayer.stopVideo();
    //clearInterval(interval)
    $("#media-player-wrapper").hide()
    $("#overlay").remove();
    $("#btn-get-tix").removeClass("video-playing")
    $("#quotes").show()
}

function onYouTubePlayerReady(playerId) {
    ytplayer = document.getElementById("media-player-object");
    ytplayer.addEventListener("onStateChange", "onPlayerStateChange");
    ytplayer.cueVideoById("tDKm9_Th7vE",'', "large");
    ytplayer.playVideo();
}


// Play video button - the big button that says play video
// $("#btn-play-video").click(function(){
//     launchVideo();
//     if($.browser.msie) {
//         $("#btn-play").trigger("click")
//     }
//     return false;
// })

// Play pause button - the play button control
$("#btn-play").click(function() {
    playVideo();
    return false;
})

$("#btn-pause").click(function() {
    pauseVideo();
    return false;
})

$("#btn-close").click(function() {
    closeVideo();
    return false;
})

$("#btn-get-tix").click(function() {
    closeVideo();
})


/*  Awesome cloud
------------------------------------------------------------------------ */

$("#awesome-cloud li a").live("click",function(event) {
    
    var pointer = $(".pointer")
    var btnClose = $(".btn-close")
    
    var reviewBubble = $("#review-bubble");
    
    // get x,y co-ords
    var position = $(this).position();
    var posTop = position.top;
    var posLeft = position.left;
    
    
    // window width
    var winWidth = $(window).width()
    
    // review bubble width plus padding
    var bubbleWidth = $(reviewBubble).outerWidth();
    var bubbleHeight = $(reviewBubble).outerHeight();
    
    // mouse position
    mouseLeft = event.pageX
    
    // distance to right side of page from mouse
    distanceToRight = winWidth - mouseLeft;
    //console.log(distanceToRight, mouseLeft, winWidth)
    
    // position review bubble, make sure it doesn't dissappear off side of page
    if (distanceToRight < bubbleWidth) {
        $(reviewBubble)
            .empty()
            .show()
            .css({
                "top": posTop + 35,
                "left": posLeft - (bubbleWidth - distanceToRight)
            })
    } else {
        $(reviewBubble)
            .empty()
            .show()
            .css({
                "top": posTop + 35,
                "left": posLeft -12
            })
    }
                        
    
    // text or word of anchor to lowercase
    var word = $(this).text().toLowerCase();
    
    // use word as pattern for new regex
    var pattern = new RegExp(word);
    
    // find reviews containing the clicked anchor
    $('.section').filter(function() {
        
        // collect page text and remove characters that don't match a-z or A-Z
        var splitTxt = $(this).text().split(/[^a-zA-Z]/);
        
        // transform array back to a string
        var joinTxt = splitTxt.join(" ");
        
        // transform to lowercase
        var txt = joinTxt.toLowerCase();
        
        // look for regex pattern in txt
        return pattern.test(txt);
        
    })
        // make clone
        .clone()
        // fill review bubble
        .appendTo("#review-bubble")
        
    // wrap content
    $(reviewBubble).wrapInner('<div class="content">')
        
    
    // create and position pointer (the little triangle below the bubble)
    $(pointer).remove();
    
    $('<div class="pointer">')
        .appendTo(this)
        .css({
            "position": "absolute",
            "top": posTop + 22,
            "left": posLeft + 12
        })
    
    // Highlight words in the bubble
    $(reviewBubble).highlight(word);
    
    // create and position close btn
    $(btnClose).remove();
    
    $('<div class="btn-close">').appendTo(reviewBubble)
    
    $(".btn-close").live("click",function(){
        $("btnClose, .pointer").remove()
        $("#review-bubble").hide()
    })
        
        
    // don't follow link
    event.preventDefault();
})

var cloud = function() {
    // get all the text, transform to lowercase, return values a-z and '
    var words = $(".section").text().toLowerCase().split(/[^a-z']+|[ \t]/)
    
    // we'll be using this to store the words we want to keep
    var cleanTxt = new Array()
    
    // don't include these words
    var stopwords = ["scottsboro","broadway","boys","old", "story", "going", "seen", "away", "just", "seeing", "walk", "night", "years", "know", "gave", "told", "far","story","stroman's","makes","toe","wait","mr","like","saw","set","stage","person","can't","you've","pause", "end","he's","i've","don't","i'll","i","isn't","i'm","it's","pulls","way","does","filled","want","feet","rape","john","joshua","ms","a", "about", "above", "above", "across", "after", "afterwards", "again", "against", "all", "almost", "alone", "along", "already", "also","although","always","am","among", "amongst", "amoungst", "amount",  "an", "and", "another", "any","anyhow","anyone","anything","anyway", "anywhere", "are", "around", "as",  "at", "back","be","became", "because","become","becomes", "becoming", "been", "before", "beforehand", "behind", "being", "below", "beside", "besides", "between", "beyond", "bill", "both", "bottom","but", "by", "call", "can", "cannot", "cant", "co", "con", "could", "couldnt", "cry", "de", "describe", "detail", "do", "done", "down", "due", "during", "each", "eg", "eight", "either", "eleven","else", "elsewhere", "empty", "enough", "etc", "even", "ever", "every", "everyone", "everything", "everywhere", "except", "few", "fifteen", "fify", "fill", "find", "fire", "first", "five", "for", "former", "formerly", "forty", "found", "four", "from", "front", "full", "further", "get", "give", "go", "had", "has", "hasnt", "have", "he", "hence", "her", "here", "hereafter", "hereby", "herein", "hereupon", "hers", "herself", "him", "himself", "his", "how", "however", "hundred", "ie", "if", "in", "inc", "indeed", "interest", "into", "is", "it", "its", "itself", "keep", "last", "latter", "latterly", "least", "less", "ltd", "made", "many", "may", "me", "meanwhile", "might", "mill", "mine", "more", "moreover", "most", "mostly", "move", "much", "must", "my", "myself", "name", "namely", "neither", "never", "nevertheless", "next", "nine", "no", "nobody", "none", "noone", "nor", "not", "nothing", "now", "nowhere", "of", "off", "often", "on", "once", "one", "only", "onto", "or", "other", "others", "otherwise", "our", "ours", "ourselves", "out", "over", "own","part", "per", "perhaps", "please", "put", "rather", "re", "same", "see", "seem", "seemed", "seeming", "seems", "serious", "several", "she", "should", "show", "side", "since", "sincere", "six", "sixty", "so", "some", "somehow", "someone", "something", "sometime", "sometimes", "somewhere", "still", "such", "system", "take", "ten", "than", "that", "the", "their", "them", "themselves", "then", "thence", "there", "thereafter", "thereby", "therefore", "therein", "thereupon", "these", "they", "thickv", "thin", "third", "this", "those", "though", "three", "through", "throughout", "thru", "thus", "to", "together", "too", "top", "toward", "towards", "twelve", "twenty", "two", "un", "under", "until", "up", "upon", "us", "very", "via", "was", "we", "well", "were", "what", "whatever", "when", "whence", "whenever", "where", "whereafter", "whereas", "whereby", "wherein", "whereupon", "wherever", "whether", "which", "while", "whither", "who", "whoever", "whole", "whom", "whose", "why", "will", "with", "within", "without", "would", "yet", "you", "your", "yours", "yourself", "yourselves", "the", "missed", "really", "staging", "characters", "created", "did", "little", "bring", "appropriate", "come", "look", "couldn't", "friends", "use", "tell", "brought", "say", "didn't", "long", "matter", "start", "subject", "needs", "th"]

    // compare two arrays, "words" and "stopwords", return only those values not in the "stopwords" array
    // and store them in the "cleanTxt" array
    for (var i in words) {
      if($.inArray(words[i], stopwords) == -1) cleanTxt.push(words[i])
    }
    
    
    
    function sortByFrequencyAndFilter(myArray)
    {
        var newArray = [];
        var freq = {};
    
        //Count Frequency of Occurances
        var i = myArray.length - 1;
        
        for (var i; i > -1; i--)
        {
            var value = myArray[i];
            //freq[value]==null?freq[value]=1:freq[value]++;
            if (freq[value] == null) {
                freq[value] = 1
            } else {
                freq[value]++
            }
            //console.log(value + " " + freq[value])
        }
        
        //Create Array of Filtered Values
        for (var value in freq)
        {
            //newArray.push(value);
            // console.log(value + " " + freq[value])
            // include words with a frequency great than 1
            if (freq[value] > 2) {
                $(".words").append('<li value="' + freq[value] + '" class="font-size-' + freq[value] + '"><a href="#">' + value + '</a></li>');
                //console.log(value + " " + freq[value])
            }
        }
        
        // Wrap the li's created above
        $(".words").wrapInner("<ul>");
        
        //Define Sort Function and Return Sorted Results
        function compareFreq(a,b)
        {
            return freq[b]-freq[a];
            
        }
        
        $.each(freq, function(index, value){
            //$(".words").append('<a href="#">' + value + '</a> ')
            //console.log(index + ' ' + value)
        })
        
        return newArray.sort(compareFreq);
    }
    
    sortByFrequencyAndFilter(cleanTxt)
    
    
    // var countDuplicates = function(array) {
    //     var dupes = {}; 
    //     var len;
    //     var freq = 0;
    //     for (var i = 0, len = array.length; i < len; i++) {
    //         var test = array[i]
    //         if (dupes[test]) {
    //             array.splice(i,1);
    //             console.log(freq)
    //             len--;
    //             i--;
    //         } else { 
    //             dupes[test] = true;
    //         }
    //     }
    // }
    // countDuplicates(cleanTxt)
    
    

    // var removeDuplicate = function(array) {
    //     var dupes = {}; 
    //     var len;
    //     for (var i = 0, len = array.length; i < len; i++) {
    //         var test = array[i]            
    //         if (dupes[test]) {
    //             console.log(test)
    //             array.splice(i,1);
    //             len--;
    //             i--;
    //         } else { 
    //             dupes[test] = true;
    //         }
    //     }
    // }
    // removeDuplicate(cleanTxt)
    
    // append our 'clean text' to the wall
    // $.each(freq, function(index, value){
    //     //$(".words").append('<a href="#">' + value + '</a> ')
    //     console.log(index)
    // })
}
cloud()

$(".words ul").tagcloud({
    type:"list",
    sizemin: 14,
    sizemax: 48
    //colormin: '555',
    //colormax: 'fff'
});

// Set cloud font-sizes
$(".words li").each(function(){
    var fontSize = parseInt($(this).css("font-size"))
    var elem = $("a", this)
    if ( fontSize < 15 ) {
        elem.css("color","#646464")
    }
    
    if ( fontSize > 15 && fontSize < 20) {
        elem.css("color","#427f91")
    }
    
    if ( fontSize > 20 && fontSize < 25) {
        elem.css("color","#f6b708")
    }
    
    if ( fontSize > 20 && fontSize < 25) {
        elem.css("color","#fcff08")
    }
    
    if ( fontSize > 25 && fontSize < 30) {
        elem.css("color","#00c4ff")
    }
    
    if ( fontSize > 30 && fontSize < 35) {
        elem.css("color","#ff3f00")
    }
    
    if ( fontSize > 35) {
        elem.css("color","#fff")
    }
    
    
      
})


//if ( wordSize < 30) wordSize.css("color","#f00 !mportant")


