/*
  Running MySource Matrix
  Developed by Squiz - http://www.squiz.net
  MySource, MySource Matrix and Squiz.net are registered Trademarks of Squiz Pty Ltd
  Page generated: 25 November 2009 12:16:14
*/


// JavaScript Document

String.prototype.trim = function() { return this.replace(/^\s+|\s+$/g, ''); }

$(document).ready(function(){
    summariseHomepageContents();
    if (!$("#case_study_box")[0]) {
        processQuotes("rt_Quotes", "#content .quotes_box","#rightcol_rotation_box");
    }
    applyFilter();
});

function applyFilter() {

    if ($("#filterContainer")[0]) {

       //-- Replace the ";" on keywords with "," --
       $("#filterContainer .record .col_keywords").each(function(){
            var keys = $(this).text();
            $(this).html(keys.replace(/;/g,","));
       });

       //-- Get the select values
       var filterState_Key = $("#filter_state").val();
       var filterState_Value = $('#filter_state :selected').text().trim();
       var filterKeywords_Key = $("#filter_keywords").val();
       var filterKeywords_Value = $('#filter_keywords :selected').text().trim();
       var csRecords;

       //-- Hide objects
       if (filterState_Key == "ALL") {
          if (filterKeywords_Key  == "ALL") {
             csRecords = $("#filterContainer tr");
             csRecords.show();
          }
          else {
             $("#filterContainer .record").hide();
             csRecords = $("#filterContainer tr[filter_keywords*='" + filterKeywords_Value + "']");
             csRecords.show();
          }
       }
       else {
          $("#filterContainer .record").hide();
          if (filterKeywords_Key  == "ALL") {
             csRecords = $("#filterContainer tr[filter_state*='" + filterState_Value + "']");
          }
          else {
             csRecords = $("#filterContainer tr[filter_state*='" + filterState_Value + "'][filter_keywords*='" + filterKeywords_Value + "']");
          }
          csRecords.show();
       }
    }
}

function resetFilter() {
    $("#filter_state").val("ALL");
    $("#filter_keywords").val("ALL");
    applyFilter();
}

jQuery.fn.getCDATA = function() {
    if($.browser.msie)
        return this[0].childNodes[0].nodeValue;
    // Other browsers do this
    return this[0].childNodes[1].nodeValue;
};

function summariseHomepageContents() {

    homeRandomContent("#tempBox_CS", "#case_study_content", randomiserContent_CS, "#cs_loading", "margin-left");

    homeRandomContent("#tempBox_PF", "#profile_content", randomiserContent_PF, "#pf_loading", "margin-right");

    $(".readmore").css("display","block");
}

function displayFirstParagraph(lookupDiv,HtmlToReplace) {

    var parags = $(lookupDiv + " p");
    var para; var prev;
    var found = false;

    for (var i=0;i<parags.length;i++) {
       para = $(lookupDiv + " p:eq(" + i + ")");

       prev = para.prev();
       if (prev != null) {
           if (prev.html() != null) {
               var content = prev.html().toUpperCase();
               if (content.indexOf("OVERVIEW") > -1) {
                   found = true;
                   break;
               }
           }
       }
    }

    if (!found) {
       para = $(lookupDiv + " p:eq(0)");;
    }

    var newHtml = "<p>" + para.html() + "</p> ";
    if ($(lookupDiv + " .readmore")[0]) {
        newHtml = newHtml + $(lookupDiv + " .readmore").html();
    }
    $(lookupDiv).html(newHtml);
}

function homeRandomContent(divHidden, divParentContent, urlToGet, divLoading, marginToAdjust) {

    var lookupContents = divHidden + " .content";
    var divToFill = divParentContent + " .content_text";

    $(divToFill).hide();
    $(divLoading).show();
    $.ajax({
        url: urlToGet,
        cache: false,
        error: function(){
            displayFirstParagraph(divToFill);
            $(divToFill).show();
        },
        success: function(htmlContent){
            $(divLoading).hide();
            $(divHidden).html(htmlContent);
            var randomInt = Math.floor(Math.random()*$(lookupContents).length)
            $(divToFill).html($(lookupContents + ":eq(" + randomInt + ")").html());

            // check if there is a thumbnail image
            if ($(divToFill + " .thumbnail").attr("src") != "") {
                $(divToFill + " .thumbnail").clone().appendTo(divParentContent + " .image");
                var width = $(divParentContent + " .image .thumbnail").attr("width");
                $(divParentContent + " .text").css(marginToAdjust, width + 20);
            }

            // display only the first paragraph as the page summary
            displayFirstParagraph(divToFill);
            $(divToFill).show();

            if (lookupContents.indexOf("_CS") != -1) {
                processQuotes("rt_Quotes", "#content .quotes_box","#rightcol_rotation_box");
            }
       }
    });
}

function processQuotes(rotationId, divToProcess, divDestination) {
    var i=0;
    var aryQuotes = [];

    $(divToProcess).each(function(){
        $(this).hide();
        $(this).find("p").each(function(){
            aryQuotes[i] = [];
            aryQuotes[i][0] = [];
            aryQuotes[i][0][0] = divDestination;
            aryQuotes[i][0][1] = $(this).html();
            i++;
        });
    });

    if (aryQuotes.length > 0) {
        //hide the link on the "on this page" section
        $("#content .onthispage li:contains('Quote')").hide();

        objRotationController.create({
            objId:rotationId,
            interval:15,
            idtofade:divDestination,
            content:aryQuotes
        });
    }
}

var objRotationController;
objRotationController = function() {

    var objRotations = {};
    var create = function(options) { add_rotation(options.objId,options) }
    var destroy = function(options) { objRotations = {}; }
    var add_rotation = function(inpId,options) {
        if(!(inpId in objRotations)) {
            objRotations[inpId] = new objRotation(options);
        };
    }
    return {
        create:create,
        destroy:destroy,
        add_rotation:add_rotation
    };

}();

function objRotation(options) {
    var o = this;
    var f_timer;
    var rotation_index = 0;
    var initial = true;
    o.interval = options.interval*1000;
    o.options = options;

    o.create = function() {
        o.replace_content(o.options);
        if (o.options.content.length > 1) {
           f_timer = setInterval(function(){o.replace_content(o.options)},o.interval);
        }
    }
    o.replace_content = function(options) {
        if (initial) {
           doreplace(options);
           initial = false;
        }
        else {
           $(options.idtofade).fadeOut(1000);
           setTimeout(function(){
              doreplace(options);
           },1000);
           $(options.idtofade).fadeIn(1000);
        }
    };

    function doreplace(options) {
           var content = options.content[rotation_index];
           for (var i=0;i<content.length;i++) {
              $(content[i][0]).html(content[i][1]);
           }

           if (rotation_index < options.content.length - 1) {
              rotation_index++;
           } else {
              rotation_index = 0;
           };
    }

    o.create();
}
